Advertisement
1988coder

394. Decode String

Feb 2nd, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/decode-string/
  2.  
  3. /**
  4.  * Recursive One Pass solution
  5.  *
  6.  * Time Complexity: O(N)
  7.  *
  8.  * Space Complexity: Depth of the recursion stack can maximum grow upto N/3.
  9.  * StringBuilder can grow upto the size of the result.
  10.  *
  11.  * Total Space Complexity: O(N/3 + M) = O(N + M).
  12.  *
  13.  * N = Length of the input string. M = Length of StringBuilder.
  14.  */
  15. class Solution {
  16.     public String decodeString(String s) {
  17.         if (s == null) {
  18.             return "";
  19.         }
  20.         if (s.length() < 4) {
  21.             return new String(s);
  22.         }
  23.  
  24.         return decodeStringHelper(s, new int[1]);
  25.     }
  26.  
  27.     private String decodeStringHelper(String s, int[] idx) {
  28.         StringBuilder sb = new StringBuilder();
  29.         int num = 0;
  30.  
  31.         while (idx[0] < s.length() && s.charAt(idx[0]) != ']') {
  32.             if (!Character.isDigit(s.charAt(idx[0]))) {
  33.                 sb.append(s.charAt(idx[0]));
  34.                 idx[0]++;
  35.             } else {
  36.                 while (Character.isDigit(s.charAt(idx[0]))) {
  37.                     num = num * 10 + s.charAt(idx[0]) - '0';
  38.                     idx[0]++;
  39.                 }
  40.  
  41.                 idx[0]++; // '['
  42.                 String tmp = decodeStringHelper(s, idx);
  43.                 idx[0]++; // ']'
  44.  
  45.                 while (num > 0) {
  46.                     sb.append(tmp);
  47.                     num--;
  48.                 }
  49.             }
  50.         }
  51.  
  52.         return sb.toString();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement