Skip to content

2330. Valid Palindrome IV

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool makePalindrome(string s) {
    int change = 0;
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      if (s[l] != s[r] && ++change > 2)
        return false;
      ++l;
      --r;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean makePalindrome(String s) {
    int change = 0;
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      if (s.charAt(l) != s.charAt(r) && ++change > 2)
        return false;
      ++l;
      --r;
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def makePalindrome(self, s: str) -> bool:
    change = 0
    l = 0
    r = len(s) - 1

    while l < r:
      if s[l] != s[r]:
        change += 1
        if change > 2:
          return False
      l += 1
      r -= 1

    return True