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

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

我的想法

brute force:
O(n2)毫无悬念的超时了

class Solution {
    public boolean validPalindrome(String s) {
        if(s == null || s.length() == 0) {
            return false;
        }
        for(int i = 0; i < s.length(); i++) {
            String str = s.substring(0, i) + s.substring(i+1, s.length());
            int head = 0, end = str.length() - 1;
            while(head < end) {
                if(str.charAt(head) != str.charAt(end)) {
                    break;
                }
                head++;
                end--;
            }
            if(head >= end) {
                return true;
            }
        }
        return false;
    }
}

two pointer:
对于删除掉一个元素可以变成回文串的字符串,如"ascbbcesa",在不相等的地方,要不然左边往前推一个要不然右边往前推一个,可以使得接下来的元素接着相等

class Solution {
    public boolean validPalindrome(String s) {
        if(s == null || s.length() == 0) {
            return false;
        }
        int head = 0, end = s.length() - 1;
        while(head < end) {
            if(s.charAt(head) != s.charAt(end)) {
                boolean left = helper(s, head + 1, end);
                boolean right = helper(s, head, end - 1);
                return (left || right);
            }
            head++;
            end--;
        }
        return true;
    }
    private boolean helper(String s, int head, int end) {
        while(head < end) {
            if(s.charAt(head) != s.charAt(end)) {
                return false;
            }
            head++;
            end--;
        }
        return true;
    }
}

解答

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值