文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。
这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
来源:力扣(LeetCode)
java实现方法1:
/**
* 解析字符串
*
* @param s 输入字符
* @return 解析后字符串
*/
public String decodeString(String s) {
char[] t = s.toCharArray();
int i = 0, n = s.length();
StringBuilder sb = new StringBuilder();
while (i < n) {
int idx = s.indexOf('[', i);
if (idx == -1) {
sb.append(s.substring(i));
break;
}
while (t[i] < '0' || t[i] > '9') {
sb.append(t[i]);
i++;
}
int len = Integer.valueOf(s.substring(i, idx));
int count = 1;
i = idx + 1;
while (count != 0) {
if (t[i] == '[') count++;
if (t[i] == ']') count--;
i++;
}
String sub = decodeString(s.substring(idx + 1, i - 1));
for (int k = 0; k < len; k++)
sb.append(sub);
}
return sb.toString();
}
时间复杂度:O(n^2)
空间复杂度:O(n)
python实现方式1:
def decode_string(s: str) -> str:
'''
解析字符串
Args:
s: 字符串
Returns:
解析后的字符串
'''
i = 0
n = len(s)
sb = []
while i < n:
idx = s.index('[',i)
if idx == -1:
sb.append(s[i:])
break
while s[i] < '0' or s[i] > '9':
sb.append(s[i])
i += 1
length = int(s[i:idx])
count = 1
i = idx + 1
while count != 0:
if s[i] == '[':
count += 1
if s[i] == ']':
count -= 1
i += 1
sub = decode_string(s[idx + 1:i - 1])
for k in range(length):
sb.append(sub)
return ''.join(sb)
时间复杂度:O(n^2)
空间复杂度:O(n)
java实现方法2:
/**
* 解析字符串,利用字符串栈和数字栈存储字符和数字
*
* @param s 输入字符
* @return 解析后字符串
*/
public String decodeString2(String s) {
if (s.indexOf('[') == -1 || s.indexOf(']') == -1) {
return s;
}
Stack<Integer> numStack = new Stack<>();
Stack<String> strStack = new Stack<>();
StringBuilder tail = new StringBuilder();
int length = s.length();
for (int i = 0; i < length; i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
int num = ch - '0';
while (i + 1 < length && Character.isDigit(s.charAt(i + 1))) {
num = num * 10 + s.charAt(i + 1) - '0';
i++;
}
numStack.add(num);
} else if (ch == '[') {
strStack.push(tail.toString());
tail = new StringBuilder();
} else if (ch == ']') {
StringBuilder temp = new StringBuilder(strStack.pop());
int times = numStack.pop();
for (int j = 0; j < times; j++) {
temp.append(tail);
}
tail = temp;
} else {
tail.append(ch);
}
}
return tail.toString();
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方法2:
def decode_string2(self, s: str) -> str:
'''
解析字符串
Args:
s: 字符串
Returns:
解析后的字符串
'''
num_stack = []
str_stack = []
sb = ""
length = len(s)
for i in range(length):
ch = s[i]
if ch.isdigit():
num = int(ch)
while i + 1 < length and s[i + 1].isdigit():
num = 10 * num + (int(s[i + 1]))
i += 1
num_stack.append(num)
elif ch == '[':
str_stack.append(sb)
sb = ''
elif ch == ']':
temp = str_stack.pop()
times = num_stack.pop()
for j in range(times):
temp += sb
sb = temp
else:
sb += ch
return sb
时间复杂度:O(n)
空间复杂度:O(n)