-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.java
More file actions
62 lines (55 loc) · 1.55 KB
/
DecodeString.java
File metadata and controls
62 lines (55 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package Leetcode;
import java.util.Stack;
public class DecodeString
{
public static void main( String[] args )
{
DecodeString decodeString = new DecodeString();
System.out.println( decodeString.decodeString( "2[ab4[c]]3[a]" ) );
}
public String decodeString( String s )
{
int num = 0;
Stack<Integer> countStack = new Stack();
Stack<String> wordStack = new Stack();
String currentString = "";
String res = "";
int index = 0;
while( index < s.length() )
{
if( Character.isDigit( s.charAt( index ) ) )
{
while( Character.isDigit( s.charAt( index ) ) )
{
num = num * 10 + ( s.charAt( index ) - '0' );
index++;
}
countStack.push( num );
}
else if( s.charAt( index ) == '[' )
{
wordStack.push( res );
res = "";
num=0;
index++;
}
else if( s.charAt( index ) == ']' )
{
int count = countStack.pop();
StringBuilder sb = new StringBuilder( wordStack.pop() );
while( count-- > 0 )
{
sb.append( res );
}
res = sb.toString();
index++;
}
else
{
res += s.charAt( index );
index++;
}
}
return res;
}
}