394.字符串解码

2020-05-28  本文已影响0人  kaikai1234

执行用时 :1 ms, 在所有 Java 提交中击败了90.09%的用户

内存消耗 :37.4 MB, 在所有 Java 提交中击败了7.69%的用户

1. 这道题耗费时间太长,1个半小时。

2. 主要在于递归,但是各种情况太复杂。主要是括号数是否为零和当前的字符。二者都要结合。导致比较复杂。

3. 代码如下:

class Solution {

    public String decodeString(String s) {

        return decodeStringHelp(s);

    }

    public String decodeStringHelp(String s){

        StringBuffer sb = new StringBuffer("");

        int count = 0;

        int left = 0;

        int right = s.length();

        StringBuffer numString = new StringBuffer("");

        int num = 0;

        int nextLeft = 0;

        while(left<right){

            if(s.charAt(left)=='['){

                left++;

                if(count==0){

                    nextLeft = left;

                }

                count++;

                continue;

            }

            if(s.charAt(left)==']'){

                count--;

                if(count==0){

                    num = Integer.parseInt(numString.toString());

                    String temp = decodeStringHelp(s.substring(nextLeft,left));

                    while(num>0){

                        sb.append(temp);

                        num--;

                    }

                    numString = new StringBuffer("");

                  num = 0;

                }

                  left++;

                continue;

            }

            if(count==0){

                if(s.charAt(left)>='0' && s.charAt(left)<='9'){

                    numString.append(s.charAt(left));

                    left++;

                    continue;

                }

                sb.append(s.charAt(left));

            }

            left++;

        }

        return sb.toString();

    }

}

上一篇 下一篇

猜你喜欢

热点阅读