394. Decode String

来源:互联网 发布:55开笑笑事件 知乎 编辑:程序博客网 时间:2024/06/05 21:56

Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".s = "3[a2[c]]", return "accaccacc".s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

思路:刚开始用递归

package l394;/* * 递归 */public class Recursive {    public String decodeString(String s) {    int idx = s.indexOf('[');    if(idx == -1)return s;    char[] cs = s.toCharArray();        StringBuilder sb = new StringBuilder();                int start = 0;        while(!(cs[start]>='0' && cs[start]<='9'))start++;        sb.append(s.substring(0, start));        int num = Integer.valueOf(s.substring(start, idx));                        int cnt = 1, i = idx+1;;        for(; i<cs.length; i++) {        if(cs[i] == '[')cnt ++;        else if(cs[i] == ']')cnt --;        if(cnt == 0) {        String next = decodeString(s.substring(idx+1, i));        for(int k=0 ;k<num; k++)sb.append(next);        break;        }        }                sb.append(decodeString(s.substring(i+1)));        return sb.toString();    }}


后来想到没次递归前,前面的不都解析出来了吗?于是想到Stack解法

package l394;import java.util.Stack;/* * Stack */public class Solution {    public String decodeString(String s) {    int idx = s.indexOf('[');    if(idx == -1)return s;    char[] cs = s.toCharArray();        StringBuilder sb = new StringBuilder();        Stack<String> stack = new Stack<String>();                for(int i=0; i<cs.length; i++) {        if(cs[i]>='0' && cs[i]<='9') {        int j = i;        while(cs[i]>='0' && cs[i]<='9')i++;        i --;        stack.push(s.substring(j, i+1));        } else if(cs[i] == '[') {        stack.push("[");        } else if(cs[i] == ']') {        StringBuilder tmp = new StringBuilder();        while(!"[".equals(stack.peek()))tmp.append(stack.pop());        stack.pop();        int num = Integer.valueOf(stack.pop());        StringBuilder ntmp = new StringBuilder();        for(int c=0; c<num; c++)ntmp.append(tmp);        stack.push(ntmp.toString());        } else {        stack.push(cs[i] + "");        }        }                while(!stack.isEmpty())sb.append(stack.pop());        return sb.reverse().toString();    }}


但是,Stack的解法时间还更长,可能是最后一个分支每次来一个字母就加到stack了比较浪费,可以用StringBUilder先存起来,再一起加到stack里面



0 0