当前位置:网站首页>Stack Title: String decoding
Stack Title: String decoding
2022-06-30 09:55:00 【The great Cherny】
List of articles
subject
Title and provenance
title : String decoding
Source :394. String decoding
difficulty
6 level
Title Description
requirement
Given an encoded string , Returns the decoded string .
The coding rule is : k[encoded_string] \texttt{k[encoded\_string]} k[encoded_string], Represents the encoded_string \texttt{encoded\_string} encoded_string Just repeat k \texttt{k} k Time . Be careful k \texttt{k} k Positive integer guaranteed .
You can think that the input string is always valid . There are no extra spaces in the input string , And the square brackets entered always meet the format requirements .
Besides , You can assume that the raw data does not contain numbers , All numbers only indicate the number of repetitions k \texttt{k} k, For example, there is no such thing as 3a \texttt{3a} 3a or 2[4] \texttt{2[4]} 2[4] The input of .
Example
Example 1:
Input : s = "3[a]2[bc]" \texttt{s = "3[a]2[bc]"} s = "3[a]2[bc]"
Output : "aaabcbc" \texttt{"aaabcbc"} "aaabcbc"
Example 2:
Input : s = "3[a2[c]]" \texttt{s = "3[a2[c]]"} s = "3[a2[c]]"
Output : "accaccacc" \texttt{"accaccacc"} "accaccacc"
Example 3:
Input : s = "2[abc]3[cd]ef" \texttt{s = "2[abc]3[cd]ef"} s = "2[abc]3[cd]ef"
Output : "abcabccdcdcdef" \texttt{"abcabccdcdcdef"} "abcabccdcdcdef"
Example 4:
Input : s = "abc3[cd]xyz" \texttt{s = "abc3[cd]xyz"} s = "abc3[cd]xyz"
Output : "abccdcdcdxyz" \texttt{"abccdcdcdxyz"} "abccdcdcdxyz"
Data range
- 1 ≤ s.length ≤ 30 \texttt{1} \le \texttt{s.length} \le \texttt{30} 1≤s.length≤30
- s \texttt{s} s Contains only lowercase English letters 、 Numbers and square brackets ‘[]’ \texttt{`[]'} ‘[]’
- s \texttt{s} s Guaranteed to be valid input
- s \texttt{s} s The range of values of all integers in is [1, 300] \texttt{[1, 300]} [1, 300]
Solution 1
Ideas and algorithms
The encoding string uses square brackets to represent fragments that need to be repeated , Square brackets may be nested , If nesting occurs , Then it is decoded from the inner layer to the outer layer . It is necessary to decode according to each pair of matching square brackets , To find the matching square brackets, you need to use the data structure of the stack , Therefore, the stack can be used to realize decoding .
Because the elements stored in the stack are characters , Include letters and square brackets , So you can use StringBuffer \texttt{StringBuffer} StringBuffer Type variable instead of stack , The following is called 「 String stack 」. Except for letters and square brackets , The encoded string also contains numbers , To distinguish between numbers and non numbers , So another stack is used to store numbers , The following is called 「 Digital stack 」. Traversing the string from left to right s s s, For each type of character , The operations are as follows :
The current character is a number , Update the number of repetitions with the current character ;
The current character is a letter , Then put the current character on the string stack ;
If the character is an open square bracket , Then a number traversal ends , Put the number of repetitions on the number stack , And put the current character on the string stack ;
If the character is a right square bracket , Then a square bracket traversal ends , Decode according to the current square bracket and the number before the square bracket , The decoding operation is as follows :
Stack the letters of the string stack in turn , Until you encounter the left square bracket , use temp \textit{temp} temp Store out of stack letters , Then pull the left square bracket from the string stack ;
take temp \textit{temp} temp reverse , After reversal temp \textit{temp} temp The alphabetical order in the string stack is the same as that of the string stack ;
The top element of the digital stack k k k Out of the stack , be temp \textit{temp} temp You need to repeat in the decoded string k k k Time , So execute k k k The second general temp \textit{temp} temp String stack operation .
After the traversal , The string stack is the decoded string in the order from the bottom of the stack to the top of the stack .
Consider the following example : s = “a3[b2[cd]]ef" s = \text{``a3[b2[cd]]ef"} s=“a3[b2[cd]]ef", The length of the encoding string is 12 12 12. The decoding operation is as follows .
Subscript 0 0 0 The character at is a letter , Put letters on the string stack . String stack is “a" \text{``a"} “a", The digital stack is [ ] [] [], Where string stack replaces stack with string , Both the string stack and the number stack are at the bottom of the stack on the left , On the right is the top of the stack .
Subscript 1 1 1 The character at is a number , Number of repetitions updated to 3 3 3.
Subscript 2 2 2 The character at is an open square bracket , Put the number of repetitions on the number stack , And put the left square bracket on the string stack . String stack is “a[" \text{``a["} “a[", The digital stack is [ 3 ] [3] [3].
Subscript 3 3 3 The character at is a letter , Put letters on the string stack . String stack is “a[b" \text{``a[b"} “a[b", The digital stack is [ 3 ] [3] [3].
Subscript 4 4 4 The character at is a number , Number of repetitions updated to 2 2 2.
Subscript 5 5 5 The character at is an open square bracket , Put the number of repetitions on the number stack , And put the left square bracket on the string stack . String stack is “a[b[" \text{``a[b["} “a[b[", The digital stack is [ 3 , 2 ] [3, 2] [3,2].
Subscript 6 6 6 and 7 7 7 The characters at are all letters , Put letters on the string stack . String stack is “a[b[cd" \text{``a[b[cd"} “a[b[cd", The digital stack is [ 3 , 2 ] [3, 2] [3,2].
Subscript 8 8 8 The character at is a right square bracket , Do the following .
Put the letters of the string stack out of the stack in turn until the left square bracket is encountered , Then pull the left square bracket from the string stack , temp = “dc" \textit{temp} = \text{``dc"} temp=“dc".
Reverse the letters out of the stack , temp = “cd" \textit{temp} = \text{``cd"} temp=“cd".
The top element of the digital stack k = 2 k = 2 k=2 Out of the stack , perform 2 2 2 The second general “cd" \text{``cd"} “cd" String stack . String stack is “a[bcdcd" \text{``a[bcdcd"} “a[bcdcd", The digital stack is [ 3 ] [3] [3].
Subscript 9 9 9 The character at is a right square bracket , Do the following .
Put the letters of the string stack out of the stack in turn until the left square bracket is encountered , Then pull the left square bracket from the string stack , temp = “dcdcb" \textit{temp} = \text{``dcdcb"} temp=“dcdcb".
Reverse the letters out of the stack , temp = “bcdcd" \textit{temp} = \text{``bcdcd"} temp=“bcdcd".
The top element of the digital stack k = 3 k = 3 k=3 Out of the stack , perform 3 3 3 The second general “bcdcd" \text{``bcdcd"} “bcdcd" String stack . String stack is “abcdcdbcdcdbcdcd" \text{``abcdcdbcdcdbcdcd"} “abcdcdbcdcdbcdcd", The digital stack is [ ] [] [].
Subscript 10 10 10 and 11 11 11 The characters at are all letters , Put letters on the string stack . String stack is “abcdcdbcdcdbcdcdef" \text{``abcdcdbcdcdbcdcdef"} “abcdcdbcdcdbcdcdef", The digital stack is [ ] [] [].
The decoded string is “abcdcdbcdcdbcdcdef" \text{``abcdcdbcdcdbcdcdef"} “abcdcdbcdcdbcdcdef".
Code
class Solution {
public String decodeString(String s) {
StringBuffer sb = new StringBuffer();
Deque<Integer> stack = new ArrayDeque<Integer>();
int num = 0;
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + c - '0';
} else if (Character.isLetter(c)) {
sb.append(c);
} else if (c == '[') {
stack.push(num);
num = 0;
sb.append(c);
} else {
int top = sb.length() - 1;
StringBuffer temp = new StringBuffer();
while (sb.charAt(top) != '[') {
temp.append(sb.charAt(top));
sb.deleteCharAt(top--);
}
sb.deleteCharAt(top--);
temp.reverse();
int k = stack.pop();
for (int j = 0; j < k; j++) {
sb.append(temp);
}
}
}
return sb.toString();
}
}
Complexity analysis
Time complexity : O ( n e + n d ) O(n_e + n_d) O(ne+nd), among n e n_e ne Is an encoded string s s s The length of , n d n_d nd Is the length of the decoded string . You need to traverse the encoding string s s s once , During decoding, you need to traverse the decoded string .
Spatial complexity : O ( n d ) O(n_d) O(nd), among n d n_d nd Is the length of the decoded string . The space complexity mainly depends on the stack space .
Solution 2
Ideas and algorithms
Solution 1 uses stack to realize decoding , You can also use recursion instead of stack .
The stack of solution one is used when encountering numbers and square brackets , The case of recursive processing is also the case of encountering numbers and square brackets . Traverse the encoded string from left to right s s s, When it comes to numbers , Get the number of repetitions , Then locate a character to the right of the left square bracket , Call recursion . The termination condition of recursion is to encounter the right square bracket , At this point, the square bracket traversal ends , Decode according to the letters in square brackets and the number of repetitions .
Code
class Solution {
int index = 0;
public String decodeString(String s) {
return recurse(s).toString();
}
public StringBuffer recurse(String s) {
StringBuffer sb = new StringBuffer();
int length = s.length();
while (index < length) {
char c = s.charAt(index);
if (c == ']') {
return sb;
} else if (Character.isDigit(c)) {
int num = 0;
while (index < length && Character.isDigit(s.charAt(index))) {
num = num * 10 + s.charAt(index) - '0';
index++;
}
index++;
StringBuffer temp = recurse(s);
for (int i = 0; i < num; i++) {
sb.append(temp);
}
} else {
sb.append(c);
}
index++;
}
return sb;
}
}
Complexity analysis
Time complexity : O ( n e + n d ) O(n_e + n_d) O(ne+nd), among n e n_e ne Is an encoded string s s s The length of , n d n_d nd Is the length of the decoded string . You need to traverse the encoding string s s s once , During decoding, you need to traverse the decoded string .
Spatial complexity : O ( n d ) O(n_d) O(nd), among n d n_d nd Is the length of the decoded string . The space complexity mainly depends on the stack space of recursive calls and the storage space of decoded strings StringBuffer \texttt{StringBuffer} StringBuffer Object of type .
边栏推荐
猜你喜欢
Design of mfc+mysql document data management system based on VS2010
Plan the IT technology route for the new year? Let's learn about Gartner infrastructure hype cycle
MySQL优化
Abstract classes and interfaces
Flume learning II - Cases
Pytorch graduate warm LR installation
Oracle cross database replication data table dblink
P. Summary of NP, NPC, NP hard and other issues
GPT (improving language understanding generative pre training) paper notes
JVM notes (III): analysis of JVM object creation and memory allocation mechanism
随机推荐
【JVM】CMS简述
Golang magic code
工作小记: sendto失败 errno 22
11. customize hooks
3.集成eslint、prettier
Differences and relationships among hyper convergence, software defined storage (SDS), distributed storage and server San
Self service terminal development process
Bluetooth BT RF test (forwarding)
Returnjson, which allows more custom data or class names to be returned
Flume learning III
Dart 开发技巧
MySQL explain
抽象类和接口
Redis docker master-slave mode and sentinel
小程序开发踩坑之旅
【JVM】G1垃圾回收器简述
八大排序(二)
Based on svelte3 X desktop UI component library svelte UI
JUL简介
Thrift easy to use