leetcode---C++实现---680. Valid Palindrome II(验证回文字符串 II)

题目

level: easy
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:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome-ii

解题思路

本题是在“验证回文字符串”基础上做了个变化,即最多可以删除一个字符,因此在判断出当前输入的字符串不满足回文字符串要求时,可删除正在遍历的两个字符中的一个,继续判断删除该字符后的字符串是否满足回文字符串的要求,如果满足,则返回true,如果仍不满足,则返回false。
判断基础回文字符串的方法为:

  1. 声明两个变量,int l 表示字符串从左往后遍历的index,int r 代表字符串从右往左遍历的index;
  2. 当 str[l] == str[r] 时,index l 往右移动,index r 往左移动,继续比较,直到 l >= r;若比较过程中出现字符不相等的情况,则不是回文字符串。

算法实现(C++)

class Solution {
public:
    bool validPalindrome(string s) {
        int l = 0;//声明index l,记录从左开始的字符串下标
        int r = s.length() - 1;//声明index r,记录从右开始的字符串下标

        while (l < r && s[l] == s[r])//当s[l] == s[r]相等时,两index往中间移动后继续比较
        {
            ++l;
            --r;
        }

        if (l < r)//若跳出了上面的while循环后,l
        {
        	//此时可以删除右边的字符,继续比较从 l 到 r-1 之间的字符是不是回文字符串
        	//也可以删除左边的字符,继续比较从 l+1 到 r 之间的字符是不是回文字符串
        	//上述两种结果只要有一个是回文字符串,则该字符满足题目要求
            return baseValidPalindrome(s, l, r-1) || baseValidPalindrome(s, l+1, r);
        }
		//若程序运行到此,则说明字符串圈闭比较完毕且都满足s[l] == s[r]后跳出的while循环,此时必是回文字符串
        return true;
    }
	
	//函数功能:比较字符串是不是基础的回文字符串
    bool baseValidPalindrome(string s, int l, int r) {
        while (l < r) {
            if (s[l] != s[r]) return false;
            else {
                ++l;
                --r;
            }
        }

        return true;
    }
};
复杂度分析
  1. 时间复杂度:O(n),若比较过程中未出现字符不相等的情况,则只需比较 n/2 次,若出现字符串不相等的情况,则需比较 m + 2*k 次,其中m+k=n;综合起来复杂度仍为O(n);
  2. 空间复杂度:O(1),只需维护有限的常量空间。

你可能感兴趣的:(leetcode刷题笔记)