Leetcode 2. Add Two Numbers
作者:互联网
C++
class Solution {
public:
vector<int> diStringMatch(string s) {
int n = s.length(), lo = 0, hi = n;
vector<int> perm(n + 1);
for (int i = 0; i < n; ++i) {
perm[i] = s[i] == 'I' ? lo++ : hi--;
}
perm[n] = lo; // 最后剩下一个数,此时 lo == hi
return perm;
}
};
Ruby
# @param {String} s
# @return {Integer[]}
def di_string_match(s)
lo = 0
hi = n = s.length
perm = Array.new(hi+1)
for i in 0...n
ch = s[i]
if ch == 'I'
perm[i] = lo
lo = lo + 1
else
perm[i] = hi
hi = hi - 1
end
end
perm[n] = lo
return perm
end
Python
class Solution:
def diStringMatch(self, s: str) -> List[int]:
lo = 0
hi = n = len(s)
perm = [0] * (n+1)
for i, ch in enumerate(s):
if ch == 'I':
perm[i] = lo
lo = lo + 1
else:
perm[i] = hi
hi = hi - 1
perm[n] = lo
return perm
Swift
class Solution {
func diStringMatch(_ s: String) -> [Int] {
let n = s.count
var lo = 0, hi = n
var perm: [Int] = Array<Int>(repeating: 0, count: n+1)
for (i, ch) in s.enumerated() {
if ch == "I" {
perm[i] = lo
lo = lo + 1
} else {
perm[i] = hi
hi = hi - 1
}
}
perm[n] = lo
return perm
}
}
标签:ch,return,lo,perm,Add,hi,Numbers,diStringMatch,Leetcode 来源: https://www.cnblogs.com/loganxu/p/16247968.html