394. Decode String

来源:互联网 发布:java面向对象解释 编辑:程序博客网 时间:2024/05/14 21:08

题目:

解码字符串,解码规则是k[str]被解码为k个str连起来的字符串

举例如下:

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


思路:递归(栈)

设置一个指针,递归的规则是:返回指针指着的字符为开始的字符串,直到指针指向字符串的末尾。

被解码的字符串分为两种:

  • 单纯的字母:如a
  • 数字和固定格式的字母:3[a]
当只是单纯地字母时,返回的字符串即为:这个字母+指针向后走一步的递归结果
是数字和固定格式的字母时,返回的字符串需要先拿出连续的数字拼接成重复次数,再用递归函数得到[符号之后的字符串的结果,返回这么多遍结果的拼接,最终移动指针跳过]符号
如果是合法字符串,那么指针是不可能指向]符号的。
递归的终止条件是指针指向了字符串的末尾。


程序

public class Solution {    int pos = 0;        //recusive: return the decoded string start with the position    public String decodeString(String s) {    String ans = "";        //if the pos comes to the end, return nothing    if(pos == s.length()) return "";        //if the pos points to a character, just return the character + string start with the next position     else if(s.charAt(pos) >= 'a' && s.charAt(pos) <= 'z') {    return s.charAt(pos++) + decodeString(s);    }        //if the pos points to a digit, store the continuous digits and calculate the times    else if(Character.isDigit(s.charAt(pos))) {    int times = 0;    //calculate the digits    while(Character.isDigit(s.charAt(pos)))     times = times * 10 + s.charAt(pos++) - '0';    //skip the '['    pos++;    //find the string start with pos    String tmp = decodeString(s);    //return the times of the pos    for(int i = 0; i < times; i++)     ans += tmp;    //skip the ']'    pos++;    return ans +decodeString(s);        } else {    return "";    }    }}


0 0
原创粉丝点击