【leetcode hot 100 394】字符串解码
解法一:一个栈用于存数字,一个栈用于存需要copy多次的String。
class Solution {
public String decodeString(String s) {
StringBuffer result = new StringBuffer();
Deque<String> stackString = new LinkedList<>();
Deque<Integer> stackInteger = new LinkedList<>();
int num = 0;
for (Character ch : s.toCharArray()) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (int) (ch - '0'); // 处理100的数
} else if (ch == '[') {
stackString.push(result.toString()); // 不能直接加,要进行toString操作
stackInteger.push(num);
result = new StringBuffer();
num = 0;
} else if (ch == ']') {
StringBuffer temp = new StringBuffer();
int copy = stackInteger.pop();
for (int i = 0; i < copy; i++) {
temp.append(result); // 这里要重新申请temp,不能result自加,容易加多
}
result = new StringBuffer(stackString.pop() + temp); // 要new不能重新赋值,只有append操作
} else {
result.append(ch);
}
}
return result.toString();
}
}
注意:
- 入栈的时候不能直接加,要进行
toString
操作:stackString.push(result.toString())
- 复制
result
的时候,要重新申请temp
,不能result
自加,容易加多:temp.append(result)
- 对
result
进行赋值时,要new
不能重新赋值,StringBuffer
只有append
操作:result = new StringBuffer(stackString.pop() + temp)
- 处理上10的数,如100:
num = num * 10 + (int) (ch - '0')
原文地址:https://blog.csdn.net/weixin_47894469/article/details/146513313
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/600830.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/600830.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!