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

[leetcode-680-Valid Palindrome II]

时间:2017-09-20 19:36:17      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:idp   star   app   http   cep   while   end   contain   div   

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‘.

 

Note:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

 思路:

从字符串两端向中间判断,如果相等则继续判断。

如果不相等,s[i] != s[j] ,那么判断 i+1到j 和i到j-1是否是回文,如果是的话即满足,都不是则不满足。

bool ispali(string& s,int start,int end)
{
    while (start <= end)
    {
        if (s[start] != s[end])return false;
        start++, end--;
    }
    return true;     
}
bool validPalindrome(string s)
{
    int n = s.length();
    if (n <= 2)return true;

    for (int i = 0; i < n;i++)
    {
        if (s[i] != s[n - i - 1])
        {
            return (ispali(s, i + 1, n - i - 1) || ispali(s, i, n - i - 2));
        }
         
    }
    return true;
}

参考:

https://leetcode.com/problems/valid-palindrome-ii/solution/#approach-2-greedy-accepted

[leetcode-680-Valid Palindrome II]

标签:idp   star   app   http   cep   while   end   contain   div   

原文地址:http://www.cnblogs.com/hellowooorld/p/7562679.html

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