• leetcode 394. 字符串解码 java


    题目:

    给定一个经过编码的字符串,返回它解码后的字符串。

    编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

    你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

    此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

    示例:

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

    解题:

    class Solution {
        public String decodeString(String s) {
            Stack<String> resStack = new Stack<>();//记录当前结果字符串
            Stack<Integer> repeatNum = new Stack<>();
    
            int rnum = 0;
            String res = "";//需要重复的字符串
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (ch == '[') {
                    resStack.push(res);
                    repeatNum.push(rnum);
                    res = "";
                    rnum = 0;
                } else if (ch == ']') {
                    int n = repeatNum.pop();
                    String tmp = resStack.pop();
                    res = tmp + repeatString(res, n);
                } else if (ch >= '0' && ch <= '9') {
                    //char 转成 int 是基础操作, 要牢记
                    rnum = 10 * rnum + ch - '0';
                } else {
                    res = res + ch;
                }
            }
            return res;
        }
    
        private String repeatString(String str, int n) {
            String curr = "";
            for (int i = 0; i < n; i++)
                curr += str;
            return curr;
        }
    }
  • 相关阅读:
    Aerospike系列:4:简单的增删改查aql
    Aerospike系列:3:aerospike特点分析
    MySQL事物系列:2:事物的实现
    MySQL事物系列:1:事物简介
    MySQL 源码系列:1:窥探篇
    MySQL 内存和CPU优化相关的参数
    Aerospike系列:2:商业版和社区版的比较
    Aerospike系列:1:安装
    MDX Cookbook 08
    MDX Cookbook 07
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11731170.html
Copyright © 2020-2023  润新知