首页 > 其他 > 详细

680. Valid Palindrome II

时间:2020-02-04 09:13:47      阅读:59      评论:0      收藏:0      [点我收藏+]

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 }

 

680. Valid Palindrome II

原文:https://www.cnblogs.com/beiyeqingteng/p/12258209.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!