394. 字符串解碼 - 力扣(LeetCode)
curr_str:遍歷整個字符串時
- 如果左邊有
[
,且無相應右括號和其匹配,那么curr_str就表示該[
到當前位置的解碼字符串 - 如果左邊的
[]
已經匹配,或者沒有[]
,curr_size就表示第一個字符到當前位置的解碼字符串
遇到字符,追加到curr_str中
遇到數字,將數字入cnt棧,注意多位數的情況
遇到[
,將curr_str入strs棧并清空curr_str
遇到]
,取出strs棧的第一個字符串str,同時取出cnt棧的棧頂數字cnt,將curr_str追加到str后,追加cnt次。最后:執行curr_str = str,以維護curr_str的含義
最后返回curr_str即可
func decodeString(s string) string {var strs []stringvar cnt []intvar curr_str stringfor i := 0; i < len(s); i++ {if s[i] >= 'a' && s[i] <= 'z' {curr_str += string(s[i])} else if s[i] >= '0' && s[i] <= '9' {c := 0for ; s[i] >= '0' && s[i] <= '9'; i++ {c = c * 10 + int(s[i] - '0')}cnt = append(cnt, c)i--;} else if s[i] == '[' {strs = append(strs, curr_str)curr_str = ""} else if s[i] == ']' {str := strs[len(strs) - 1]strs = strs[:len(strs) - 1]c := cnt[len(cnt) - 1]cnt = cnt[:len(cnt) - 1]for c != 0 {str += curr_strc--}curr_str = str}}return curr_str
}
739. 每日溫度 - 力扣(LeetCode)
遍歷數組,將元素與下標push進棧,如果當前元素大于棧頂元素,出棧直到當前元素小于棧頂元素,維護ans數組,ans[出棧元素的下標] = 當前元素下標 - 出棧元素下標
如果最后有剩余元素,這些元素的ans為0
class Solution {
public:vector<int> dailyTemperatures(vector<int>& temperatures) {stack<pair<int, int>> stk;vector<int> ans(temperatures.size());for (size_t i = 0; i < temperatures.size(); i++) {if (!stk.empty() && temperatures[i] > stk.top().first) {while (!stk.empty() && temperatures[i] > stk.top().first) {auto t = stk.top();stk.pop();ans[t.second] = i - t.second;}}stk.push({temperatures[i], i});}return ans;}
};