返回介绍

solution / 2300-2399 / 2330.Valid Palindrome IV / README_EN

发布于 2024-06-17 01:03:07 字数 3356 浏览 0 评论 0 收藏 0

2330. Valid Palindrome IV

中文文档

Description

You are given a 0-indexed string s consisting of only lowercase English letters. In one operation, you can change any character of s to any other character.

Return true_ if you can make _s_ a palindrome after performing exactly one or two operations, or return _false_ otherwise._

 

Example 1:

Input: s = "abcdba"
Output: true
Explanation: One way to make s a palindrome using 1 operation is:
- Change s[2] to 'd'. Now, s = "abddba".
One operation could be performed to make s a palindrome so return true.

Example 2:

Input: s = "aa"
Output: true
Explanation: One way to make s a palindrome using 2 operations is:
- Change s[0] to 'b'. Now, s = "ba".
- Change s[1] to 'b'. Now, s = "bb".
Two operations could be performed to make s a palindrome so return true.

Example 3:

Input: s = "abcdef"
Output: false
Explanation: It is not possible to make s a palindrome using one or two operations so return false.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists only of lowercase English letters.

Solutions

Solution 1

class Solution:
  def makePalindrome(self, s: str) -> bool:
    i, j = 0, len(s) - 1
    cnt = 0
    while i < j:
      cnt += s[i] != s[j]
      i, j = i + 1, j - 1
    return cnt <= 2
class Solution {
  public boolean makePalindrome(String s) {
    int cnt = 0;
    int i = 0, j = s.length() - 1;
    for (; i < j; ++i, --j) {
      if (s.charAt(i) != s.charAt(j)) {
        ++cnt;
      }
    }
    return cnt <= 2;
  }
}
class Solution {
public:
  bool makePalindrome(string s) {
    int cnt = 0;
    int i = 0, j = s.size() - 1;
    for (; i < j; ++i, --j) {
      cnt += s[i] != s[j];
    }
    return cnt <= 2;
  }
};
func makePalindrome(s string) bool {
  cnt := 0
  i, j := 0, len(s)-1
  for ; i < j; i, j = i+1, j-1 {
    if s[i] != s[j] {
      cnt++
    }
  }
  return cnt <= 2
}
function makePalindrome(s: string): boolean {
  let cnt = 0;
  let i = 0;
  let j = s.length - 1;
  for (; i < j; ++i, --j) {
    if (s[i] != s[j]) {
      ++cnt;
    }
  }
  return cnt <= 2;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文