Given a string `S` that only contains "I" (increase) or "D" (decrease), let `N = S.length`.
Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:
- If
S[i] == "I", thenA[i] < A[i+1] - If
S[i] == "D", thenA[i] > A[i+1]
Example 1:
Input: "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: "III"
Output: [0,1,2,3]
Example 3:
Input: "DDI"
Output: [3,2,0,1]
Note:
1 <= S.length <= 10000Sonly contains characters"I"or"D".
這道題給了一個只有 'D' 和 'I' 兩個字母組成的字符串,表示一種 pattern,其中 'D' 表示需要下降 Decrease,即當前數字大於下個數字,同理,'i' 表示需要上升 Increase,即當前數字小於下個數字,讓返回符合這個要求的任意一個數組,還有個要求是該數組必須是 [0, n] 之間的所有數字的一種全排列,其中n是給定 pattern 字符串的長度。這表明了返回數組不能有重復數字,這里一會上升一會下降的,很容易產生重復數字,難不成還要不停的檢測是否有重復數字么,不,這樣太麻煩了,必須想一種生成方法來保證絕對不會有重復數字。對於上升來說,可以從0開始累加,而對於下降來說,則可以從n開始下降,這樣保證了在結束之前二者絕不會相遇,到最后一個數字的時候二者相同,再將這個相同數字加入即可,因為返回的數組的個數始終會比給定字符串長度大1個,參見代碼如下:
class Solution {
public:
vector<int> diStringMatch(string S) {
vector<int> res;
int n = S.size(), mn = 0, mx = n;
for (char c : S) {
if (c == 'I') res.push_back(mn++);
else res.push_back(mx--);
}
res.push_back(mx);
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/942
參考資料:
https://leetcode.com/problems/di-string-match/
https://leetcode.com/problems/di-string-match/discuss/194906/C%2B%2B-4-lines-high-low-pointers
https://leetcode.com/problems/di-string-match/discuss/194904/C%2B%2BJavaPython-Straight-Forward
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)
