标签:bool 字符 inpu most str 分析 int bsp one
Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba" Output: True
Example 2:
Input: "abca" Output: True Explanation: You could delete the character ‘c‘.
分析:
先用两个指针: i, j 分别指向字符串的两端,然后一个往前移,一个往后移动。如果遇到不一样,则要么跳过i,要么跳过j,再不断比较。
1 class Solution { 2 public boolean validPalindrome(String s) { 3 for (int i = 0, j = s.length() - 1; i < j; i++, j--) 4 if (s.charAt(i) != s.charAt(j)) { 5 int i1 = i, j1 = j - 1, i2 = i + 1, j2 = j; 6 while (i1 < j1 && s.charAt(i1) == s.charAt(j1)) {i1++; j1--;}; 7 while (i2 < j2 && s.charAt(i2) == s.charAt(j2)) {i2++; j2--;}; 8 return i1 >= j1 || i2 >= j2; 9 } 10 return true; 11 } 12 }
标签:bool 字符 inpu most str 分析 int bsp one
原文地址:https://www.cnblogs.com/beiyeqingteng/p/12258209.html