Leetcode394.字符串解码
Posted xdcat
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode394.字符串解码相关的知识,希望对你有一定的参考价值。
1 class Solution { 2 public int ptr = 0; 3 public String decodeString(String s) { 4 LinkedList<String> stk = new LinkedList<>(); 5 while(ptr < s.length()){ 6 char cur = s.charAt(ptr); 7 System.out.println(ptr+" "+cur); 8 if(Character.isDigit(cur)){ 9 stk.addLast(getDigit(s));//【可能是多位的,一个完整的数,不一定是单个数字】 10 } 11 else if(Character.isLetter(cur) || cur == ‘[‘){ 12 stk.addLast(String.valueOf(s.charAt(ptr))); 13 ptr++; 14 } 15 else{ 16 ++ptr; 17 LinkedList<String> sub = new LinkedList<>(); 18 while(!"[".equals(stk.peekLast())){ 19 sub.addLast(stk.removeLast()); 20 } 21 stk.removeLast(); 22 Collections.reverse(sub); 23 int repeatNum = Integer.valueOf(stk.removeLast()); 24 String curStr = getString(sub); 25 StringBuilder sb = new StringBuilder(); 26 while(repeatNum > 0){ 27 sb.append(curStr); 28 repeatNum--; 29 } 30 stk.addLast(sb.toString()); 31 } 32 } 33 return getString(stk); 34 } 35 public String getString(LinkedList<String> sub){ 36 StringBuilder sb = new StringBuilder(); 37 for(String s: sub){ 38 sb.append(s); 39 } 40 return sb.toString(); 41 } 42 public String getDigit(String s){ 43 StringBuilder sb = new StringBuilder(); 44 while(Character.isDigit(s.charAt(ptr))){ 45 sb.append(s.charAt(ptr)); 46 ptr++; 47 } 48 return sb.toString(); 49 } 50 }
以上是关于Leetcode394.字符串解码的主要内容,如果未能解决你的问题,请参考以下文章