1750. Minimum Length of String After Deleting Similar Ends - Medium

前往題目

想法

  • 雙指針

思路

  1. 雙指針,指向兩端
  2. l指針小於r,也都指向同樣的字符,持續循環
  3. 每個循環都盡可能的移動左指針和右指針
  4. 輸出剩下幾個字符

Code

class Solution {
    public int minimumLength(String s) {
        int l = 0, r = s.length() - 1;

        // Until intersect or characters don't match
        while (l < r && s.charAt(l) == s.charAt(r)) {
            char ch = s.charAt(l);

            // Shift left pointer
            while (l <= r && s.charAt(l) == ch) {
                ++l;
            }

            // Shift right pointer
            while (l <= r && s.charAt(r) == ch) {
                --r;
            }
        }
        return r - l + 1;
    }
}

1750. Minimum Length of String After Deleting Similar Ends - Medium
https://f88083.github.io/2024/07/09/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/
作者
Simon Lai
發布於
2024年7月9日
許可協議