leetcode394. String Decoding

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], which means that the square brackets are encoded_stringrepeated exactly the number of ktimes. Note kthat it is guaranteed to be a positive integer.

You can assume that the input string is always valid; the input string has no extra spaces, and the input square brackets are always well-formed.

Also, you can think that the original data does not contain numbers, all numbers just represent the number of repetitions k, for example no input like 3aor 2[4].

Example 1:
 Input: s = "3[a]2[bc]"
 Output: "aaabcbc"

Example 2:
 Input: s = "3[a2[c]]"
 Output: "accaccacc"

Idea:
The input string may have nested brackets. At this time, we first decode the strings in the inner brackets, and then decode the strings in the outer brackets in turn, that is to say, we go from left to When traversing the string right, the [internal string traversed first will be decoded later, which is in line with the characteristics of the first-in, last-out stack, so we can solve this problem with the help of the stack.

Traversing the input string is done as follows:

  • The traversal is the number, first extract the complete number string, and then push the stack.
  • The traversal is the letter or '[', and it is directly pushed onto the stack.
  • The traversal is to ']'first obtain the string to be copied, and then copy it. It is best to push the copied string back onto the stack.

When traversed ']', the specific operation steps are as follows:

  1. First pop the stack, save the popped string to the vector, stop popping the stack until the '[' is popped, and the '[' is not saved to the vector.
  2. Then invert the contents of the vector, because the order of popping is opposite to the order of stacking.
  3. Then, several strings to be copied are spliced ​​to obtain the final string to be copied.
  4. Pop the number string at the top of the stack at this time and convert it to the integer num.
  5. Copy the string to be copied num times, and finally get the copied string.
  6. Push the copied string onto the stack.

Finally, when the input string is traversed, the final decoded string is obtained by splicing the strings in the stack.

Animated demo: The
insert image description here
code is as follows:

class Solution {
    
    
public:
	//从字符串s的pos位置开始,提取数字字符串
	string GetNum(string& s, size_t& pos)
	{
    
    
		string num;
		while (s[pos] != '[')
		{
    
    
			num += s[pos];
			pos++;
		}
		return num;
	}
	//将vector当中的字符串拼接后进行返回
	string GetString(vector<string>& st)
	{
    
    
		string s;
		for (auto e : st)
		{
    
    
			s += e;
		}
		return s;
	}
	string decodeString(string s) {
    
    
		vector<string> st; //数组模拟栈
		size_t pos = 0; //用于遍历字符串s
		while (pos < s.size())
		{
    
    
			//1、遍历到的是数字,先将完整的数字字符串提取出来,然后进行压栈
			if (isdigit(s[pos]))
			{
    
    
				string num = GetNum(s, pos);
				st.push_back(num);
			}
			//2、遍历到的是字母或'[',直接将其进行压栈
			else if (isalpha(s[pos]) || s[pos] == '[')
			{
    
    
				st.push_back(string(1, s[pos]));
				pos++;
			}
			//3、遍历到的是']',先获取到待复制的字符串,再将其进行复制,最好将复制后的字符串重新进行压栈
			else
			{
    
    
				vector<string> sub; //待复制的若干字符串
				//a、先进行弹栈,将弹出的字符串保存到vector当中,直到'['被弹出时停止弹栈,'['不保存到vector中
				while (st.back() != "[")
				{
    
    
					sub.push_back(st.back());
					st.pop_back();
				}
				st.pop_back();

				//b、再将vector当中的内容进行逆置,因为出栈的顺序与入栈顺序相反
				reverse(sub.begin(), sub.end());

				//c、然后将待复制的若干字符串进行拼接,得到最终待复制的字符串
				string all = GetString(sub);

				//d、弹出此时栈顶的数字字符串,并将其转换成整数num
				int num = stoi(st.back());
				st.pop_back();

				//d、将待复制的字符串复制num次,最终得到复制后的字符串
				string str; //复制后的字符串
				while (num--)
				{
    
    
					str += all;
				}

				//e、将复制后的字符串进行压栈
				st.push_back(str);

				pos++;
			}
		}
		return GetString(st); //将栈当中的字符串拼接后进行返回
	}
};

Code description:

  • The code does not use the real stack, but uses the vector to simulate the push and pop of the stack, in order to facilitate the traversal from the bottom of the stack to the top of the stack. (This is an important point)
  • The parameter pos of the GetNum function needs to be passed by reference to ensure that we are always using the same pos variable to traverse the string.

Guess you like

Origin blog.csdn.net/chenlong_cxy/article/details/123239282