棧之字符串解碼

在這裏插入圖片描述
注意:

  • 拼接時把兩個括號直接字符都拿過來,注意順序
  • 考慮多位數的情況
  • 結果拼接順序
class Solution {
    public String decodeString(String s) {
       String res = "";
		Stack<String> stack = new Stack<>();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ']') {
				String code = "";
				while (!stack.peek().equals("[")) {
					code = stack.pop() + code;
				}
				stack.pop();
				String strNum = "";
				while (!stack.isEmpty() && (stack.peek().charAt(0) >= '0' && stack.peek().charAt(0) <= '9')) {
					strNum = stack.pop() + strNum;
				}
				int num = Integer.valueOf(strNum);
				String str = "";
				for (int j = 0; j < num; j++) {
					str = str + code;
				}
				stack.push(str);
			} else {
				String string = "" + s.charAt(i);
				stack.push(string);
			}

		}
		while (!stack.isEmpty()) {
			res = stack.pop() + res;
		}
		return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章