[LeetCode] 2330. Valid Palindrome IV

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.

有效的回文 IV。

给你一个下标从 0 开始、仅由小写英文字母组成的字符串 s 。在一步操作中,你可以将 s 中的任一字符更改为其他任何字符。

如果你能在 恰 执行一到两步操作后使 s 变成一个回文,则返回 true ,否则返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-palindrome-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个字符串,你只能修改最多两处,请判断你是否能将这个字符串修改成一个回文串。

思路是双指针从两边往中间逼近,应该算是 easy 题。直接给代码。

时间O(n)

空间O(1)

Java实现

复制代码
 1 class Solution {
 2     public boolean makePalindrome(String s) {
 3         int left = 0;
 4         int right = s.length() - 1;
 5         int k = 2;
 6         while (left < right) {
 7             if (s.charAt(left) != s.charAt(right)) {
 8                 k--;
 9             }
10             if (k < 0) {
11                 return false;
12             }
13             left++;
14             right--;
15         }
16         return true;
17     }
18 }
复制代码

 

LeetCode 题目总结

posted @   CNoodle  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2022-07-20 [LeetCode] 792. Number of Matching Subsequences
2020-07-20 [LeetCode] 1180. Count Substrings with Only One Distinct Letter
2020-07-20 [LeetCode] 1100. Find K-Length Substrings With No Repeated Characters
点击右上角即可分享
微信分享提示