680. Valid Palindrome II*

680. Valid Palindrome II*

https://leetcode.com/problems/valid-palindrome-ii/

题目描述

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.

C++ 实现 1

s[i] != s[j] 的时候, 要么删除 s[i], 要么删除 s[j]. 只要有一种情况能得到 Palindrome 字符串, 那么就可以返回 true.

class Solution {
private:
	// 用 dir 表示移动方向, +1 表示 ++i, 相当于删除 s[i]
	// -1 表示 --j, 相当于删除 s[j]
	// 使用 count 记录删除次数, 最多一次
    bool isPalindrome(const string &s, int dir) {
        int i = 0, j = s.size() - 1;
        int count = 0;
        while (i <= j) {
            if (s[i] != s[j]) {
                if (dir == 1) ++ i;
                else if (dir == -1) -- j;
                ++ count;
                if (count > 1) return false;
                continue;
            }
            ++ i;
            -- j;
        }
        return true;
    }
public:
    bool validPalindrome(string s) {
        auto a = isPalindrome(s, 1); // 删除 s[i]
        auto b = isPalindrome(s, -1); // 删除 s[j]
        return a || b;
    }
};

C++ 实现 2

LeetCode 的 Submission 中的一种做法. 用 s.erase(i, 1) 直接删除 s[i]… 其中判断某字符是否为回文串的代码可以学习, 因为我一直用对撞指针来判断回文串. 这里直接用 reverse 后的字符串和原字符串相同.

发现还是用对撞指针好… 这里要额外分配一个 string.

bool valid(string s) {
      string tmp = s;
      std::reverse(tmp.begin(), tmp.end());
      if( tmp == s ) return true;
      else return false;
}

下面是最后的实现代码:

class Solution {
public:
    bool validPalindrome(string s) {
      int i = 0, j = s.length()-1;
      string tmp = s;
      
      while( i < j ){
        if( s[i] == s[j] ) ++i, --j;
        else{
          string s1 = s.erase(i,1);
          string s2 = tmp.erase(j,1);
          if( valid(s1) ) return true;
          else if( valid(s2)) return true;
          else return false;
        }
      }
      return true;
    }
    bool valid(string s){
      string tmp = s;
      std::reverse(tmp.begin(), tmp.end());
      if( tmp == s ) return true;
      else return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值