代码实现时,由于每次都选择的是最小数和最大数,我们可以用两个变量 lo 和 hi 表示当前剩余数字中的最小数和最大数。
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defdiStringMatch(self, s: str) -> List[int]: lo = 0 hi = n = len(s) perm = [0] * (n + 1) for i, ch inenumerate(s): if ch == 'I': perm[i] = lo lo += 1 else: perm[i] = hi hi -= 1 perm[n] = lo # 最后剩下一个数,此时 lo == hi return perm
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { 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; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11
classSolution { publicint[] diStringMatch(String s) { intn= s.length(), lo = 0, hi = n; int[] perm = newint[n + 1]; for (inti=0; i < n; ++i) { perm[i] = s.charAt(i) == 'I' ? lo++ : hi--; } perm[n] = lo; // 最后剩下一个数,此时 lo == hi return perm; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11
publicclassSolution { publicint[] DiStringMatch(string s) { int n = s.Length, lo = 0, hi = n; int[] perm = newint[n + 1]; for (int i = 0; i < n; ++i) { perm[i] = s[i] == 'I' ? lo++ : hi--; } perm[n] = lo; // 最后剩下一个数,此时 lo == hi return perm; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcdiStringMatch(s string) []int { n := len(s) perm := make([]int, n+1) lo, hi := 0, n for i, ch := range s { if ch == 'I' { perm[i] = lo lo++ } else { perm[i] = hi hi-- } } perm[n] = lo // 最后剩下一个数,此时 lo == hi return perm }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9
var diStringMatch = function(s) { let n = s.length, lo = 0, hi = n; const perm = newArray(n + 1).fill(0); for (let i = 0; i < n; ++i) { perm[i] = s[i] === 'I' ? lo++ : hi--; } perm[n] = lo; // 最后剩下一个数,此时 lo == hi return perm; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10
int* diStringMatch(char * s, int* returnSize) { int n = strlen(s), lo = 0, hi = n; int *perm = (int *)malloc(sizeof(int) * (n + 1)); for (int i = 0; i < n; ++i) { perm[i] = s[i] == 'I' ? lo++ : hi--; } perm[n] = lo; // 最后剩下一个数,此时 lo == hi *returnSize = n + 1; return perm; }