classSolution: defminimumSteps(self, s: str) -> int: n = len(s) left, right = 0, n - 1 ans = 0 while left < right: while left < right and s[left] == '0': # find the first 1 from left left += 1 while left < right and s[right] == '1': # find the first 0 from right right -= 1 if left < right: # if left < right, we need to swap s[right] to position left ans += right - left # the number of swaps needed left += 1 right -= 1 return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: longlongminimumSteps(string s){ longlong ans = 0; int left = 0, right = s.size() - 1; while (left < right) { while (left < right && s[left] == '0') left++; while (left < right && s[right] == '1') right--; if (left < right){ ans += right - left; left++; right--; } } return ans; } };
classSolution: defminimumSteps(self, s: str) -> int: ans = 0 cnt = 0# 每次遇到 0 時,左邊的 1 的數量 for ch in s: if ch == '1': cnt += 1 else: ans += cnt return ans
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: longlongminimumSteps(string s){ int n = s.size(), cnt = 0; longlong ans = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') cnt++; else ans += cnt; } return ans; } };
寫在最後
Cover photo is generated by @ゴリラの素材屋さん, thanks for their work!