394. Decode String

Link

Solution

這題分別透過兩個stack去紀錄 count根要repeat的words。 實作上有一些地方要注意。 words是記錄當遇到 ']' 時要被repeat 的字串,所以每次repeat的結果要跟下次要repeat的parcial string做結合

words一開始要給一個空字串,以確保上述提到的結合不會有問題

public String decodeString(String s) {
        Stack<Integer> times = new Stack<>();
        String nums = "";
        Stack<String> words = new Stack<>();
        words.push("");//給予空值
        for(int i = 0; i < s.length(); i++){
            if(Character.isDigit(s.charAt(i))){
                while(Character.isDigit(s.charAt(i))){
                    nums += s.charAt(i);
                    i++;
                }
                times.push(Integer.parseInt(nums));
                nums = "";
            }
            
            if(s.charAt(i) == '['){
               words.push("");
            }
            else if ( s.charAt(i) == ']'){
                int count = times.pop();
                String word = words.pop();
                String ret = "";
                while(count > 0){
                    ret += word;
                    count--;
                }
                words.push(words.pop() + ret); //結合下次要repeat的word
            }
            else{
                words.push(words.pop() + s.charAt(i));
            }
        }
        return words.pop();

Last updated

Was this helpful?