Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c1fbea5

Browse files
committed
solve 394.字符串解码
1 parent f91508b commit c1fbea5

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

‎zh/394.字符串解码.java‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* @lc app=leetcode.cn id=394 lang=java
3+
*
4+
* [394] 字符串解码
5+
*
6+
* https://leetcode-cn.com/problems/decode-string/description/
7+
*
8+
* algorithms
9+
* Medium (50.12%)
10+
* Likes: 372
11+
* Dislikes: 0
12+
* Total Accepted: 46.4K
13+
* Total Submissions: 87.9K
14+
* Testcase Example: '"3[a]2[bc]"'
15+
*
16+
* 给定一个经过编码的字符串,返回它解码后的字符串。
17+
*
18+
* 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
19+
*
20+
* 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
21+
*
22+
* 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
23+
*
24+
*
25+
*
26+
* 示例 1:
27+
*
28+
* 输入:s = "3[a]2[bc]"
29+
* 输出:"aaabcbc"
30+
*
31+
*
32+
* 示例 2:
33+
*
34+
* 输入:s = "3[a2[c]]"
35+
* 输出:"accaccacc"
36+
*
37+
*
38+
* 示例 3:
39+
*
40+
* 输入:s = "2[abc]3[cd]ef"
41+
* 输出:"abcabccdcdcdef"
42+
*
43+
*
44+
* 示例 4:
45+
*
46+
* 输入:s = "abc3[cd]xyz"
47+
* 输出:"abccdcdcdxyz"
48+
*
49+
*
50+
*/
51+
52+
// @lc code=start
53+
class Solution {
54+
55+
int index = 0;
56+
57+
public String decodeString(String s) {
58+
int len = s.length();
59+
int num = 0;
60+
StringBuilder sb = new StringBuilder();
61+
62+
while (index < len) {
63+
char ch = s.charAt(index++);
64+
if ('0' <= ch && ch <= '9') {
65+
num = num * 10 + (ch - '0');
66+
} else if (ch == '[') {
67+
String temp = decodeString(s);
68+
for (int j = 0; j < num; j++) {
69+
sb.append(temp);
70+
}
71+
num = 0;
72+
} else if (ch == ']') {
73+
return sb.toString();
74+
} else {
75+
sb.append(ch);
76+
}
77+
}
78+
79+
return sb.toString();
80+
}
81+
}
82+
// @lc code=end
83+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /