博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解码字符串 Decode String
阅读量:4321 次
发布时间:2019-06-06

本文共 1969 字,大约阅读时间需要 6 分钟。

2018-11-14 17:56:12

问题描述:

问题求解:

方法一、递归求解

最直观的解法就是递归来求了,并且很显然的这个问题可以使用递归来进行求解。

public String decodeString(String s) {        StringBuffer sb = new StringBuffer();        int num = 0;        for (int i = 0; i < s.length(); i++) {            if (Character.isDigit(s.charAt(i))) {                num = 0;                while (i < s.length() && Character.isDigit(s.charAt(i))) {                    num = num * 10 + (s.charAt(i) - '0');                    i++;                }                i--;            }            else if (s.charAt(i) == '[') {                int count = 1;                int j = i;                while (count != 0) {                    j++;                    if (s.charAt(j) == '[') count++;                    if (s.charAt(j) == ']') count--;                }                String tmp = decodeString(s.substring(i + 1, j));                for (int k = 1; k < num; k++) sb.append(tmp);                i = j;            }            else sb.append(s.charAt(i));        }        return sb.toString();    }

方法二、使用Stack求解

使用Stack求解的时候,最核心的思路就是当遇到'['的时候将当前sb 和 num进行压栈操作,当遇到‘]’的时候将堆栈中sb 和 num取出并对当前的字符串进行num次重复并串联到sb后面。

public String decodeString(String s) {        StringBuffer sb = new StringBuffer();        Stack
stack1 = new Stack<>(); Stack
stack2 = new Stack<>(); int k = 0; for (char c : s.toCharArray()) { if (Character.isDigit(c)) k = k * 10 + c - '0'; else if (c == '[') { stack1.push(sb); stack2.push(k); sb = new StringBuffer(); k = 0; } else if (c == ']') { int count = stack2.pop(); String tmp = sb.toString(); sb = stack1.pop(); for (int i = 0; i < count; i++) sb.append(tmp); } else sb.append(c); } return sb.toString(); }

 

转载于:https://www.cnblogs.com/TIMHY/p/9959407.html

你可能感兴趣的文章
DataNode 工作机制
查看>>
windows系统下安装MySQL
查看>>
错误提示总结
查看>>
实验二+070+胡阳洋
查看>>
Linux IPC实践(3) --具名FIFO
查看>>
Qt之模拟时钟
查看>>
第一次接触安卓--记于2015.8.21
查看>>
(转)在分层架构下寻找java web漏洞
查看>>
mac下多线程实现处理
查看>>
C++ ifstream ofstream
查看>>
跟初学者学习IbatisNet第四篇
查看>>
seL4环境配置
查看>>
Git报错:insufficient permission for adding an object to repository database .git/objects
查看>>
ajax跨域,携带cookie
查看>>
BZOJ 1600: [Usaco2008 Oct]建造栅栏( dp )
查看>>
洛谷 CF937A Olympiad
查看>>
Codeforces Round #445 C. Petya and Catacombs【思维/题意】
查看>>
用MATLAB同时作多幅图
查看>>
python中map的排序以及取出map中取最大最小值
查看>>
ROR 第一章 从零到部署--第一个程序
查看>>