LeetCode0680.验证回文字符串 Ⅱ

题目要求:

算法分析

判断回文串,可使用头尾双指针。因为回文串满足以下条件,若回文串两侧的字符相同,则删去两侧字符后剩下的字符串仍为回文串。

本题的特殊要求是,最多可以删除一个字符,所以双指针向中间行进的过程中可以有一次删除相异字符的机会,

因为头尾指针的两个字符不同,所以可以删掉头字符,或者删掉尾字符,

分别判断两种情况下的字符串是否为回文串即可。

代码展示(C#)

 1 public class Solution {
 2      public bool ValidPalindrome(string s)
 3     {
 4         if (s.Length < 2) return true;
 5         int i = 0;
 6         int j = s.Length - 1;
 7         while( i < j)
 8         {
 9             if(s[i] != s[j])
10             {
11                 return IsPalindrome(s, i+1, j) || IsPalindrome(s, i, j-1);
12             }
13             ++i;
14             --j;
15         }
16         return true;
17     }
18     public bool IsPalindrome(string s, int i ,int j)
19     {
20         while (i < j)
21         {
22             if (s[i++] != s[j--])
23             {
24                 return false;
25             }
26         }
27         return true;
28     }
29 }

提交结果

 

猜你喜欢

转载自www.cnblogs.com/KingR/p/12927241.html