LeetCode Solutions
942. DI String Match
Time: Space:
class Solution {
public:
vector<int> diStringMatch(string S) {
vector<int> ans;
int min = 0;
int max = S.length();
for (const char c : S)
ans.push_back(c == 'I' ? min++ : max--);
ans.push_back(min);
return ans;
}
};
class Solution {
public int[] diStringMatch(String S) {
final int n = S.length();
int[] ans = new int[n + 1];
int min = 0;
int max = n;
for (int i = 0; i < n; ++i)
ans[i] = S.charAt(i) == 'I' ? min++ : max--;
ans[n] = min;
return ans;
}
}
class Solution:
def diStringMatch(self, S: str) -> List[int]:
ans = []
mini = 0
maxi = len(S)
for c in S:
if c == 'I':
ans.append(mini)
mini += 1
else:
ans.append(maxi)
maxi -= 1
ans.append(mini)
return ans