zoukankan      html  css  js  c++  java
  • 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
    

    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.

    解题思路:

    首先想到的是暴力破解法,对每一个字母以及不删除进行尝试看能否构成一个回文字符串。

    显然,超时了_(:з」∠)_

    其实我们可以一开始就检查是否是回文字符串,如果遇到s[left] != s[right]的情况,我们可以尝试删除left或者right来进行判断是否是回文字符串

    代码:

    class Solution {
    public:
        bool validPalindrome(string s) {
            int left = 0;
            int right = s.size() -1;
            bool moved = false;
            while(left < right){
                if(left == right)
                    break;
                if(s[left] != s[right]){
                    if(isPalindromeWithoutChar(s, left))
                        return true;
                    if(isPalindromeWithoutChar(s, right))
                        return true;
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    private:
        bool isPalindromeWithoutChar(string &s, int idx){
            int left = 0;
            int right = s.size() - 1;
            while(left < right){
                if(left == idx)
                    left++;
                else if(right == idx)
                    right--;
                if(s[right] != s[left])
                    return false;
                left++;
                right--;
            }
            return true;
        }
    };
  • 相关阅读:
    ELK搭建
    php 高效日志记录扩展seaslog 的使用
    linux批量修改文件中包含字符串的查找替换
    goaccess
    mysql启动错误,提示crash 错误
    laravel config 配置无效
    地址重写 No input file specified的解决方法
    redis 一些操作命令
    RNN与LSTM
    最大熵推导LR
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9194367.html
Copyright © 2011-2022 走看看