博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Decode String
阅读量:6660 次
发布时间:2019-06-25

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

Given an encoded string, return it's decoded string.The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].Examples:s = "3[a]2[bc]", return "aaabcbc".s = "3[a2[c]]", return "accaccacc".s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

 这道题感觉挺难的,迭代的思想感觉不太容易想

  1. Iterate through the entire string (while loop and idx++)
  2. if the current char is number (isDigit()), convert string to int
  3. if the current char is ‘[’(next is a char ), push res to strStack, clean res
  4. if the current char is ‘]’ (build the res string), append res to previous string in strStack
  5. if the current char is letter (we don’t know what’s next), add it to res

 

class Solution {    public String decodeString(String s) {        if(s == null || s.length() == 0){            return "";        }        Stack
numStack = new Stack<>(); Stack
strStack = new Stack<>(); int count = 0; StringBuilder res = new StringBuilder(); for(int i =0; i< s.length(); i++){ char c = s.charAt(i); //find number if(c >= '0' && c <= '9'){ count = 10 * count + c - '0'; } //find left square brackets else if(c == '['){ numStack.push(count); strStack.push(res.toString()); count = 0; res = new StringBuilder(); } //find right square brackets else if( c == ']'){ StringBuilder temp = new StringBuilder(strStack.pop()); int repeat = numStack.pop(); for(int j = 0; j < repeat; j++){ temp.append(res); } res = temp; } //find normal character else{ res.append(c); } } return res.toString(); }}

 

转载于:https://www.cnblogs.com/incrediblechangshuo/p/9733713.html

你可能感兴趣的文章
数据挖掘topic
查看>>
eclipse 插件管理和使用
查看>>
m0n0wall安装配置
查看>>
双向链表
查看>>
前端工程师的进阶之路
查看>>
Go 语言环境变量设置
查看>>
Centos7 配置 sendmail、postfix 端口号25、465
查看>>
ActiveMQ - 初体验,探讨JMS通信模型
查看>>
解密FFmpeg播放状态控制内幕
查看>>
路由器的密码恢复
查看>>
Scenario 6 –HP C7000 Virtual Connect FlexFabric SUS with A/A Uplinks, 8
查看>>
CentOS6.3 64位安装wine出错,牛人帮帮忙
查看>>
我的友情链接
查看>>
python简介
查看>>
python文件读写,以后就用with open语句
查看>>
精通脚本***学习笔记(二)
查看>>
typedef用法
查看>>
【Android必备】应用小部件概述(23)
查看>>
IOS图片的拉伸技巧
查看>>
semaphore.h
查看>>