Java Simple Solution(No Recursive) - Easy to understand


  • 0
    T

    public class Solution {
    public String decodeString(String s) {
    String res = "";
    int left=0;
    int right=0;
    s = " "+s+" ";
    for(int i=0;i<s.length();i++){
    if(s.charAt(i)=='[') left = i;
    if(s.charAt(i)==']'){
    right = i;
    int num = 0;
    for(int j=left-1;j>=0;j--){
    if(!(s.charAt(j)>='0'&&s.charAt(j)<='9')){
    left = j+1;
    break;
    }
    if(j==0) left = j+1;
    }
    String temp_left = s.substring(0,left);
    String temp_mid = s.substring(left,right+1);
    String temp_right = s.substring(right+1,s.length());
    s = temp_left + helper(temp_mid) + temp_right;
    i=0;
    }
    }
    return s.trim();
    }
    private String helper(String s){
    String res = "";
    String freq = "";
    String temp = "";
    int num = 0;
    for(int i=0;i<s.length();i++){
    if(s.charAt(i)>='0'&&s.charAt(i)<='9') {
    freq = freq+s.charAt(i);
    num = Integer.valueOf(freq);
    }
    if(s.charAt(i)=='[') temp = "";
    if(s.charAt(i)>='a'&&s.charAt(i)<='z') temp = temp + s.charAt(i);
    if(s.charAt(i)==']'){
    for(int j=0;j<num;j++)
    res = res + temp;
    }
    }
    return res;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.