|
| 1 | +package stack; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | +/** |
| 5 | + * Created by gouthamvidyapradhan on 12/04/2018. |
| 6 | + * Given an encoded string, return it's decoded string. |
| 7 | + * <p> |
| 8 | + * The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated |
| 9 | + * exactly k times. Note that k is guaranteed to be a positive integer. |
| 10 | + * <p> |
| 11 | + * You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. |
| 12 | + * <p> |
| 13 | + * Furthermore, you may assume that the original data does not contain any digits and that digits are only for those |
| 14 | + * repeat numbers, k. For example, there won't be input like 3a or 2[4]. |
| 15 | + * <p> |
| 16 | + * Examples: |
| 17 | + * <p> |
| 18 | + * s = "3[a]2[bc]", return "aaabcbc". |
| 19 | + * s = "3[a2[c]]", return "accaccacc". |
| 20 | + * s = "2[abc]3[cd]ef", return "abcabccdcdcdef". |
| 21 | + * |
| 22 | + * Solution: Maintain a stack and push items when a character other than ] is encountered. When a character ] is |
| 23 | + * encountered pop elements, build string and duplicate it. |
| 24 | + */ |
| 25 | +public class DecodeString { |
| 26 | + |
| 27 | + /** |
| 28 | + * Main method |
| 29 | + * |
| 30 | + * @param args |
| 31 | + * @throws Exception |
| 32 | + */ |
| 33 | + public static void main(String[] args) throws Exception { |
| 34 | + System.out.println(new DecodeString().decodeString("100[leetcode]")); |
| 35 | + } |
| 36 | + |
| 37 | + public String decodeString(String s) { |
| 38 | + Stack<Character> stack = new Stack<>(); |
| 39 | + for (int i = 0; i < s.length(); i++) { |
| 40 | + if (s.charAt(i) == ']') { |
| 41 | + StringBuilder stackBuff = new StringBuilder(); |
| 42 | + while (stack.peek() != '[') { |
| 43 | + stackBuff.append(stack.pop()); |
| 44 | + } |
| 45 | + stack.pop(); //pop '[' |
| 46 | + String num = ""; |
| 47 | + while (!stack.isEmpty() && !Character.isAlphabetic(stack.peek()) && stack.peek() != '[') { |
| 48 | + num = stack.pop() + num; |
| 49 | + } |
| 50 | + String str = stackBuff.reverse().toString(); |
| 51 | + StringBuilder stringMultiple = new StringBuilder(); |
| 52 | + int N = Integer.parseInt(num); |
| 53 | + while (N-- > 0) { |
| 54 | + stringMultiple.append(str); |
| 55 | + } |
| 56 | + for (int j = 0; j < stringMultiple.length(); j++) { |
| 57 | + stack.push(stringMultiple.charAt(j)); |
| 58 | + } |
| 59 | + } else stack.push(s.charAt(i)); |
| 60 | + } |
| 61 | + StringBuilder result = new StringBuilder(); |
| 62 | + while (!stack.isEmpty()) { |
| 63 | + result.append(stack.pop()); |
| 64 | + } |
| 65 | + return result.reverse().toString(); |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments