码迷,mamicode.com
首页 > 其他好文 > 详细

680. Valid Palindrome II

时间:2018-01-20 22:45:35      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:col   lin   判断   val   --   指针   div   int   output   

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Input: "aba"
Output: True
Input: "abca"
Output: True
Explanation: You could delete the character c.

判断字符串是不是回文,最多可以删除字符串的一个元素来使它成为回文。

解决:从字符串两端开始比较,用一个指针low从前遍历,用high从尾部遍历。

1、当s[low] == s[high],说明符合回文,++low, --high,遍历下一组。

2、要是s[low] != s[high],就要删除一个数,重组。重组的原则就是s[low]和s[high-1]比较,s[high]和s[low+1]比较,是否能配对。

2.1、要是s[low+1] == s[high],那就删除当前的s[low];对应的s[low] == s[high-1],就删除当前的s[high]。

2.2、要是两个都符合条件,就要顺次看下一对能不能组合。

2.3、要是两个都不符合条件,那就说明只删除一个元素不能形成回文。

class Solution {
public:
    bool validPalindrome(string s) {
        int low = 0;
        int high = s.length() - 1;
        int cnt = 0;
        while (low<high) {
            if (s[low] != s[high]) {
                if (s[low+1] == s[high] && s[low] == s[high-1]) {
                    if (s[low+1] == s[high] && s[low+2] == s[high-1])
                        ++low;
                    else if (s[low] == s[high-1] && s[low+1] == s[high-2])
                        --high;

                }
                else if (s[low+1] == s[high])
                    ++low;
                else if (s[low] == s[high-1])
                    --high;
                else
                    return false;
                ++cnt;
            }
            if (cnt==2)
                return false;
            ++low;
            --high;
        }
        return true;
    }
};

 

680. Valid Palindrome II

标签:col   lin   判断   val   --   指针   div   int   output   

原文地址:https://www.cnblogs.com/Zzz-y/p/8322046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!