LeetCode#680: Valid Palindrome II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83900469

Description

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

Example

Input: "aba"
Output: True
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.

Solution

考虑这个测试用例: mlcupuuffuupuculm,当判断到'c' != 'u'的时候,我们要选择究竟是删除’c’还是’u’,因为无论删除哪个字符,下一个要比较的字符都相等,然而再往下就不一定相等了。因此,我们用return isPalindrome(s, i+1, j) || isPalindrome(s, i, j-1);判断分别删除’c’和’u’之后的字符串是否是回文,而在这个判断的过程中,如果再发现有字符不相等,根据题目要求只允许删除一个字符,因此直接返回false。

这种解法有可能第一个字符串就不相等,转而执行isPalindrome(s, i+1, j)时也有可能到最后才判断不相等返回false,这时候由于||再执行isPalindrome(s, i, j-1);,也就是说,整个操作最多扫描数组2 * n次,因此时间复杂度为O(n)。

public class Solution {
    public boolean validPalindrome(String s) {
        int i = 0;
        int j = s.length() - 1;
        while(i < j) {
        	if(s.charAt(i) != s.charAt(j)) 
        		return isPalindrome(s, i+1, j) || isPalindrome(s, i, j-1);
        	i++;
        	j--;
        }
        return true;
    }
    
    private boolean isPalindrome(String s, int i, int j) {
    	while(i < j) {
    		if(s.charAt(i) != s.charAt(j)) return false;
    		i++;
    		j--;
    	}
    	return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/83900469