Given an encoded string, return it’s decoded string. For example, given “3[a2[b]]”, return “abbabbabb”.
https://leetcode.com/problems/decode-string/
Java Solution
The key to solve this problem is convert the string to a structured data structure and recursively form the return string.
class Solution { public String decodeString(String s) { Stack<Exp> stack = new Stack<>(); Exp e = new Exp(1); stack.push(e); String num = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') { num = num + c; } else if (c == '[') { if (num.length() == 0) continue; int value = Integer.parseInt(num); num = ""; Exp exp = new Exp(value); stack.push(exp); } else if (c == ']') { Exp top = stack.pop(); stack.peek().list.add(top); } else { stack.peek().list.add(new Exp(c)); } } Exp root = stack.pop(); return root.getStr(); } } class Exp { int count; List<Exp> list; char c; public Exp(int num) { count = num; list = new ArrayList<>(); } public Exp(char ch) { c = ch; } public String getStr() { String result = ""; if (list != null) { for (int i = 0; i < count; i++) { for (Exp e : list) { result += e.getStr(); } } } else { result += c; } return result; } } |
Solution Using two stacks.
class Solution {
public String decodeString(String s) {
Stack nums=new Stack();
Stack str =new Stack();
str.push("");
int len=s.length();
int i=0;
while(i<len){
String num="";
while(i<len && '0'<=s.charAt(i) && s.charAt(i)<='9'){
num=num+s.charAt(i);
i++;
}
if(!num.equals("")){
nums.push(Integer.valueOf(num));
}
else if(s.charAt(i)=='['){
str.push("[");
str.push("");
i++;
}
else if(s.charAt(i)==']'){
String sf="";
Stack temp =new Stack();
while( !str.isEmpty()&& !"[".equals(str.peek()) ){
temp.push(str.pop());
}
while( !temp.isEmpty())
{
sf+=temp.pop();
}
String x= str.pop();
str.push(getMultipliedString(sf,nums.pop()) );
i++;
}
else{
if( !str.isEmpty()&& i<len && !"[".equals(str.peek()) ){
str.push(str.pop()+s.charAt(i));
}
i++;
}
}//end of main while loop
String sf="";
Stack temp =new Stack();
while( !str.isEmpty()&& !"[".equals(str.peek()) ){
temp.push(str.pop());
}
while( !temp.isEmpty()){
sf+=temp.pop();
}
return sf;
}
String getMultipliedString(String x,int n){
String res="";
while(n-->0){
res+=x;
}
return res;
}
}