题目描述
开心!!独立思考字符串题,还AC了,成就感满满 XD 难点应该是在于嵌套括号,那么这里实际上还要考虑到一个类似于括号匹配的事情 谈到括号,那么大概率用到栈
思路 & 代码
当前栈帧,只解决一层 的括号,如果内嵌了括号,那么把当前层内的整个字符串 放入下一层进行递归处理。 举个例子:3[a2[c]],那么把 a2[c] 放入下层栈帧处理,返回成 3[acc],再继续变成 accaccacc 栈的作用:得到放入下层的字符串(最外层括号结束判断)
class Solution {
public String decodeString ( String s) {
StringBuffer ans = new StringBuffer ( ) ;
Stack < Character > leftStack = new Stack < > ( ) ;
int nowNum = 0 ;
for ( int i = 0 ; i < s. length ( ) ; i++ ) {
if ( s. charAt ( i) >= '0' && s. charAt ( i) <= '9' ) {
int numJ = i + 1 ;
nowNum = s. charAt ( i) - '0' ;
while ( s. charAt ( numJ) != '[' ) {
nowNum *= 10 ;
nowNum += s. charAt ( numJ) - '0' ;
numJ++ ;
}
for ( int j = numJ; ; j++ ) {
if ( s. charAt ( j) == '[' ) {
leftStack. push ( s. charAt ( i + 1 ) ) ;
}
else if ( s. charAt ( j) == ']' ) {
leftStack. pop ( ) ;
if ( leftStack. isEmpty ( ) ) {
String temp = decodeString ( s. substring ( numJ + 1 , j) ) ;
for ( int k = 0 ; k < nowNum; k++ ) {
ans. append ( temp) ;
}
i = j;
break ;
}
}
}
}
else {
ans. append ( s. charAt ( i) ) ;
}
}
return ans. toString ( ) ;
}
}
数字不一定是个位数,还要进行一个字符串转数字处理 用 StringBuffer,最后返回 toString() 比较好 循环比较多,而且每个栈帧本质上都是一次循环,所以要小心死循环等情况。
更新版
class Solution {
public String decodeString ( String s) {
Deque < Integer > stack = new ArrayDeque < > ( ) ;
char [ ] arr = s. toCharArray ( ) ;
StringBuilder sb = new StringBuilder ( ) ;
for ( int i = 0 ; i < arr. length; i++ ) {
if ( arr[ i] >= '0' && arr[ i] <= '9' ) {
int num = 0 ;
while ( arr[ i] >= '0' && arr[ i] <= '9' ) {
num *= 10 ;
num += arr[ i++ ] - '0' ;
}
for ( int j = i; ; j++ ) {
if ( arr[ j] == '[' ) {
stack. push ( j) ;
}
else if ( arr[ j] == ']' ) {
stack. pop ( ) ;
if ( stack. isEmpty ( ) ) {
String temp = decodeString ( s. substring ( i + 1 , j) ) ;
for ( int k = 0 ; k < num; k++ ) {
sb. append ( temp) ;
}
i = j;
break ;
}
}
}
}
else {
sb. append ( arr[ i] ) ;
}
}
return sb. toString ( ) ;
}
}