算法练习(3)—— 栈

来源:互联网 发布:怎么修复excel软件 编辑:程序博客网 时间:2024/06/05 20:44

算法练习(3)—— 栈

习题

本次题目取自leetcode中的 Depth-first Search 栏目中的第394题:
Decode String


上题:

Description

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].

Example

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

思路与代码

1.题意还是挺简单的。就是让你重复输出某些字符,而且题目也说了不会给你错误的形式。不过这里说一下leetcode测试代码的两个样例,一个是 "" ,一个是 "leetcode" ,这两个一个是没有输入,一个是没有 [] 的形式。要自己注意加特殊判断…

2.归类于深搜,但是看到这种有多层的而且是最里层最先得到结果的,第一时间想到的就是栈了。具体想法就是把数字和字母分类压两个栈,根据 ] 来进行出栈输出。写的比较不简洁,主要是因为根据测试代码改了好几遍…不过应该还是能看懂吧~


代码如下:

#include <string>#include <stack>using namespace std;class Solution {public:    string decodeString(string s) {        if (s.length() == 0)            return "";        int i = 0;        stack<int> num;        stack<string> result;        while (i < s.length()) {            if (isNumber(s[i])) {                int start = i;                while (isNumber(s[i + 1]))                    i++;                int count = 0, mul = 1;                for (int j = i; j >= start; j--) {                    count += (s[j] - '0') * mul;                    mul *= 10;                }                num.push(count);            }            else if (s[i] == '[') {                result.push("");            }            else if (s[i] == ']') {                string ss = result.top();                result.pop();                int repeat = num.top();                num.pop();                string r = "";                for (int k = 0; k < repeat; k++)                    r += ss;                if (!result.empty()) {                    string next = result.top();                    result.pop();                    result.push(next + r);                }                else {                    result.push(r);                }            }            else {                if (!result.empty()) {                    string next = result.top();                    result.pop();                    result.push(next + s[i]);                }                else {                    string ss = "";                    ss += s[i];                    result.push(ss);                }            }            i++;        }        return result.top();    }    bool isNumber(char ch) {        if (ch <= '9' && ch >= '0')            return true;        return false;    }};
阅读全文
0 0
原创粉丝点击