classSolution: defsmallestNumber(self, pattern: str) -> str: i, cur, n = 0, 1, len(pattern) ans = [''] * (n + 1) while i < n: if i and pattern[i] == 'I': i += 1 while i < n and pattern[i] == 'I': ans[i] = digits[cur] cur += 1 i += 1 i0 = i while i < n and pattern[i] == 'D': i += 1 for j inrange(i, i0 - 1, -1): ans[j] = digits[cur] cur += 1 return''.join(ans)
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public String smallestNumber(String pattern) { inti=0, n = pattern.length(); varcur='1'; varans=newchar[n + 1]; while (i < n) { if (i > 0 && pattern.charAt(i) == 'I') ++i; for (; i < n && pattern.charAt(i) == 'I'; ++i) ans[i] = cur++; vari0= i; while (i < n && pattern.charAt(i) == 'D') ++i; for (varj= i; j >= i0; --j) ans[j] = cur++; } returnnewString(ans); } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: string smallestNumber(string pattern){ int i = 0, n = pattern.length(); char cur = '1'; string ans(n + 1, 0); while (i < n) { if (i && pattern[i] == 'I') ++i; for (; i < n && pattern[i] == 'I'; ++i) ans[i] = cur++; int i0 = i; while (i < n && pattern[i] == 'D') ++i; for (int j = i; j >= i0; --j) ans[j] = cur++; } return ans; } };
funcsmallestNumber(pattern string)string { n := len(pattern) ans := make([]byte, n+1) for i, cur := 0, byte('1'); i < n; { if i > 0 && pattern[i] == 'I' { i++ } for ; i < n && pattern[i] == 'I'; i++ { ans[i] = cur cur++ } i0 := i for ; i < n && pattern[i] == 'D'; i++ { } for j := i; j >= i0; j-- { ans[j] = cur cur++ } } returnstring(ans) }