Skip to content

Latest commit

 

History

History
122 lines (93 loc) · 2.84 KB

File metadata and controls

122 lines (93 loc) · 2.84 KB

中文文档

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

Python3

class Solution:
    def makePalindrome(self, s: str) -> bool:
        i, j = 0, len(s) - 1
        t = 0
        while i < j:
            if s[i] != s[j]:
                t += 1
            i, j = i + 1, j - 1
        return t <= 2

Java

class Solution {
    public boolean makePalindrome(String s) {
        int t = 0;
        for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
            if (s.charAt(i) != s.charAt(j)) {
                ++t;
            }
        }
        return t <= 2;
    }
}

C++

class Solution {
public:
    bool makePalindrome(string s) {
        int t = 0;
        for (int i = 0, j = s.size() - 1; i < j; ++i, --j) t += s[i] != s[j];
        return t <= 2;
    }
};

Go

func makePalindrome(s string) bool {
	t := 0
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		if s[i] != s[j] {
			t++
		}
	}
	return t <= 2
}

TypeScript

...