📜  解码递归编码为 count 后跟 substring | 的字符串第 2 组(使用递归)

📅  最后修改于: 2022-05-13 01:56:10.634000             🧑  作者: Mango

解码递归编码为 count 后跟 substring | 的字符串第 2 组(使用递归)

给出一个编码字符串str 。字符串编码的模式如下。

任务是解码这个字符串str

例子:

迭代方法:迭代方法在本题的Set-1中提到。

递归方法:在本文中,将使用递归堆栈来解决问题。按照下面提到的方法解决问题

  • 声明一个堆栈
  • 递归遍历给定字符串的每个字符。可能有4种情况:
    • 情况 1:当前字符为'['
      • 在这种情况下不需要做任何事情。继续下一个字符
    • 案例 2:当前字符是']'
      • 从堆栈中弹出顶部字符串temp顶部整数 x
      • 重复字符串temp,x 次
      • 如果堆栈中的下一个顶部元素是字符串,则将此重复的字符串附加到顶部字符串
      • 否则将重复的字符串压入堆栈
    • 情况 3:当前字符是数字
      • 如果原始字符串的前一个字符也是数字,则将此数字附加到堆栈顶部的数字
      • 如果前一个字符是其他字符,则将此数字压入堆栈
    • 案例 4:当前字符是一个字母
      • 如果原始字符串的前一个字符也是字母表,则将此字母表附加到堆栈顶部的字符串
      • 如果前一个字符是其他字符,则将此字母表推入堆栈
  • 最后返回栈中的字符串并打印

下面是上述方法的实现。

C++
// C++ code to implement above approach
#include 
using namespace std;
 
// Stack to store intermediate strings
stack ans;
string res = "";
 
// Recusrsive function to decode
// the encoded string
void decode(string s, int i)
{ 
    if (i == s.length()) {
        res = ans.top();
        return;
    }
     
    // If the string character is '['
    if (s[i] == '[');
     
    // If the string character is ']'
    else if (s[i] == ']') { 
        string temp = ans.top();
        ans.pop();
        int x = stoi(ans.top());
        ans.pop();
        for (string j = temp; x > 1; x--)
            temp = temp + j;
        string temp1
            = ans.empty() == false ?
            ans.top() : "";
         
        if (!temp1.empty() &&
            !(temp1[0] - '0' < 10)) {
            ans.pop();
            temp1 = temp1 + temp;
            ans.push(temp1);
        }
        else {
            ans.push(temp);
        }
    }
   
    // If string character is a digit
    else if (s[i] - '0' < 10) {     
        string temp =
            ans.empty() == false ?
            ans.top() : "";
       
        if (!temp.empty() &&
            temp[0] - '0' < 10
            && s[i - 1] - '0' < 10) {
            ans.pop();
            temp = temp + s[i];
            ans.push(temp);
        }
        else {
            temp = s[i];
            ans.push(temp);
        }     
    }
     
    // If the string character is alphabet
    else if (s[i] - 'a' < 26) {     
        string temp =
            ans.empty() == false ?
            ans.top() : "";
       
        if (!temp.empty() &&
            temp[0] - 'a' >= 0
            && temp[0] - 'a' < 26) {
            ans.pop();
            temp = temp + s[i];
            ans.push(temp);
        }
        else {
            temp = s[i];
            ans.push(temp);
        }   
    }
     
    // Recursive call for next index
    decode(s, i + 1);
}
 
// Function to call the recursive function
string decodeString(string s)
{
    decode(s, 0);
    return res;
}
 
// Driver code
int main()
{
    string str = "2[a2[b]]";
    cout << decodeString(str) << endl;
    return 0;
}


Java
// Java code to implement above approach
import java.util.*;
class GFG{
 
  // Stack to store intermediate Strings
  static Stack ans = new Stack();
  static String res = "";
 
  // Recusrsive function to decode
  // the encoded String
  static void decode(char[] s, int i)
  { 
    if (i == s.length) {
      res = ans.peek();
      return;
    }
 
    // If the String character is '['
    if (s[i] == '[');
 
    // If the String character is ']'
    else if (s[i] == ']') { 
      String temp = ans.peek();
      ans.pop();
      int x = Integer.valueOf(ans.peek());
      ans.pop();
      for (String j = temp; x > 1; x--)
        temp = temp + j;
      String temp1
        = ans.isEmpty() == false ?
        ans.peek() : "";
 
      if (!temp1.isEmpty() &&
          !(temp1.charAt(0) - '0' < 10)) {
        ans.pop();
        temp1 = temp1 + temp;
        ans.add(temp1);
      }
      else {
        ans.add(temp);
      }
    }
 
    // If String character is a digit
    else if (s[i] - '0' < 10) {     
      String temp =
        ans.isEmpty() == false ?
        ans.peek() : "";
 
      if (!temp.isEmpty() &&
          temp.charAt(0) - '0' < 10
          && s[i - 1] - '0' < 10) {
        ans.pop();
        temp = temp + s[i];
        ans.add(temp);
      }
      else {
        temp = String.valueOf(s[i]);
        ans.add(temp);
      }     
    }
 
    // If the String character is alphabet
    else if (s[i] - 'a' < 26) {     
      String temp =
        ans.isEmpty() == false ?
        ans.peek() : "";
 
      if (!temp.isEmpty() &&
          temp.charAt(0) - 'a' >= 0
          && temp.charAt(0) - 'a' < 26) {
        ans.pop();
        temp = temp + s[i];
        ans.add(temp);
      }
      else {
        temp = String.valueOf(s[i]);
        ans.add(temp);
      }   
    }
 
    // Recursive call for next index
    decode(s, i + 1);
  }
 
  // Function to call the recursive function
  static String decodeString(String s)
  {
    decode(s.toCharArray(), 0);
    return res;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String str = "2[a2[b]]";
    System.out.print(decodeString(str) +"\n");
  }
}
 
// This code is contributed by shikhasingrajput


Python3
# Python code to implement above approach
 
# Stack to store intermediate strings
ans = []
res = ""
 
# Recusrsive function to decode
# the encoded string
def decode(s, i):
    global res
    global ans
    if (i == len(s)):
        res = ans[len(ans) - 1]
        return
 
    # If the string character is '['
    if (s[i] == '['):
        pass
 
    # If the string character is ']'
    elif (s[i] == ']'):
        temp = ans[len(ans) - 1]
        ans.pop()
        x = int(ans[len(ans) - 1])
        ans.pop()
        j = temp
        while(x>1):
            temp = temp + j
            x -= 1
        temp1 = ans[len(ans) - 1] if len(ans) != 0 else ""
 
        if len(temp1) != 0 and ~(ord(temp1[0]) - ord('0') < 10):
            ans.pop()
            temp1 = temp1 + temp
            ans.append(temp1)
        else:
            ans.append(temp)
 
    # If string character is a digit
    elif(ord(s[i]) - ord('0') < 10):
        temp = ans[len(ans) - 1] if len(ans) != 0 else ""
 
        if(len(temp) != 0 and
            ord(temp[0]) - ord('0') < 10 and
            ord(s[i - 1]) - ord('0') < 10):
            ans.pop()
            temp = temp + s[i]
            ans.append(temp)
        else:
            temp = s[i]
            ans.append(temp)
 
    # If the string character is alphabet
    elif (ord(s[i]) - ord('a') < 26):
        temp = ans[len(ans) - 1]  if (len(ans) != 0) else ""
 
        if(temp != 0 and ord(temp[0]) - ord('a') >= 0 and ord(temp[0]) - ord('a') < 26):
            ans.pop()
            temp = temp + s[i]
            ans.append(temp)
        else:
            temp = s[i]
            ans.append(temp)
 
    # Recursive call for next index
    decode(s, i + 1)
 
# Function to call the recursive function
def decodeString(s):
    decode(s, 0)
    return res
 
# Driver code
str = "2[a2[b]]"
print(decodeString(str))
 
# This code is contributed by shinjanpatra


Javascript


输出
abbabb

时间复杂度: O(N) 其中 N 是解码字符串的长度
辅助空间: O(N)