题目
题目链接:
https://www.nowcoder.com/practice/130e1a9eb88942239b66e53ec6e53f51
思路
直接看答案,不难
参考答案C++
class Solution {public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param str string字符串* @return bool布尔型*/bool palindrome(string str) {// 双指针int n = str.size();int L = 0;int R = n - 1;int diff = 0; //可以删除的数量while (L <= R) {if (str[L] == str[R]) {L++;R--;} else {if (diff > 0) return false;if (str[L + 1] == str[R]) {L++;diff++;} else if (str[L] == str[R - 1]) {R--;diff++;} else {return false;}}}return true;}
};
参考答案Java
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param str string字符串* @return bool布尔型*/public boolean palindrome (String str) {//双指针int n = str.length();int L = 0, R = n - 1;int diff = 0;while (L <= R) {if (str.charAt(L) == str.charAt(R)) {L++;R--;} else {if (diff > 0) return false; //不止有1个位置的值不一样if (str.charAt(L + 1) == str.charAt(R)) {L++;diff = 1;} else if (str.charAt(L) == str.charAt(R - 1)) {R--;diff = 1;} else {return false; //忽略掉2个还是不行,返回false}}}return true;}
}
参考答案Go
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param str string字符串* @return bool布尔型*/
func palindrome(str string) bool {//双指针n := len(str)L := 0R := n - 1diff := 0 //可以删除的个数for L <= R {if str[L] == str[R] {L++R--} else {if diff > 0 {return false}if str[L+1] == str[R] {L++diff++} else if str[L] == str[R-1] {R--diff++} else {return false}}}return true
}
参考答案PHP
<?php/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param str string字符串 * @return bool布尔型*/
function palindrome( $str )
{// 双指针$n = strlen($str);$L=0;$R= $n-1;$diff = 0;while ($L<=$R){if($str[$L]==$str[$R]){$L++;$R--;}else{if($diff >0) return false;if($str[$L+1] == $str[$R]){$L++;$diff++;}else if($str[$L] == $str[$R-1]){$R--;$diff++;}else{return false;}}}return true;
}