美文网首页
刷题(3)leetcode 680. Valid Palindr

刷题(3)leetcode 680. Valid Palindr

作者: MuMuMiu | 来源:发表于2022-01-05 08:55 被阅读0次

这道题目是easy tag,题目让判断,在至多删除一个字符的情况下,给定的字符串是不是回文。tricky的地方是,当你发现两边字符不一样的时候,该删除左边还是右边。

e.g: "ebcbbececabbacecbbcbe", "abca"

Solution: two pointers, recursive

my solution:

class Solution {

    public boolean validPalindrome(String s) {

        return isValid(s, false);

    }

    private boolean isValid(String s, boolean flag) {

        int left = 0, right = s.length() - 1;

        while (left<=right) {

            if(s.charAt(left) != s.charAt(right)) {

                if(flag) {

                    return false;

                } else {

                    flag = true;

                    StringBuilder sleft = new StringBuilder(s);

                    StringBuilder sright = new StringBuilder(s);

                    return isValid(sleft.deleteCharAt(left).toString(), true) || isValid(sright.deleteCharAt(right).toString(), true);

                }

            } else {

                left++;

                right--;

            }

        }

        return true;

    }

}

time complexity: O(n), recursive means touch every node once

space complexity: O(n), in this case, we only recursive at most once

相关文章

网友评论

      本文标题:刷题(3)leetcode 680. Valid Palindr

      本文链接:https://www.haomeiwen.com/subject/tyrhcrtx.html