Leetcode394——Decode String

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. 问题描述

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 or 2[4].

Examples:

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

中文

给定一个经过编码的字符串,返回其解码字符串。编码规则为:k[encoded_string],其中中括号内的encoded_string被重复k次。注意k一定是正整数。

2. 求解

本题中明显有括号的匹配问题,因此需要使用栈来求解。当碰到右括号(])时,字符串出栈,碰到左括号([)时,保存左右括号内的字符串([]),继续出栈,保存字符串重复次数,直至栈为空或碰到非数字。要注意重复次数不是个位数,将字符串重复之后压入栈中。继续处理剩余字符串,同样执行上述过程,直至处理完字符串。然后将栈中所有的字符出栈构成结果字符串返回。

public class Solution {
    public String decodeString(String s) {
        int n = s.length();
        Stack stack = new Stack();
        String result = "";
        String temp = "";
        for (int i = 0; i < n; i ++) {
            char str = s.charAt(i);
            if (str != ']') {
                stack.push(str);
            } else {
                char ch = stack.pop();
                while (ch != '[') {
                    temp = ch + temp;
                    ch = stack.pop();
                }
                //字符串重复次数
                String times = "";
                while(!stack.isEmpty()) {
                    ch = stack.pop();
                    if(Character.isDigit(ch)) {
                        times = ch + times;
                    }else {
                        stack.push(ch);
                        break;
                    }
                }
                //重复字符串,压入栈中
                for(int j = 0; j < Integer.parseInt(times); j++) {
                    for(int k = 0; k < temp.length(); k++) {
                        stack.push(temp.charAt(k));
                    }
                }
                temp = "";
            }
        }
        while(!stack.isEmpty()) {
            result = stack.pop() + result;
        } 
        return result;
    }
}

你可能感兴趣的:(Leetcode394——Decode String)