zoukankan      html  css  js  c++  java
  • LeetCode0680.验证回文字符串 Ⅱ

    题目要求:

    算法分析

    判断回文串,可使用头尾双指针。因为回文串满足以下条件,若回文串两侧的字符相同,则删去两侧字符后剩下的字符串仍为回文串。

    本题的特殊要求是,最多可以删除一个字符,所以双指针向中间行进的过程中可以有一次删除相异字符的机会,

    因为头尾指针的两个字符不同,所以可以删掉头字符,或者删掉尾字符,

    分别判断两种情况下的字符串是否为回文串即可。

    代码展示(C#)

    public class Solution {
         public bool ValidPalindrome(string s)
        {
            if (s.Length < 2) return true;
            int i = 0;
            int j = s.Length - 1;
            while( i < j)
            {
                if(s[i] != s[j])
                {
                    return IsPalindrome(s, i+1, j) || IsPalindrome(s, i, j-1);
                }
                ++i;
                --j;
            }
            return true;
        }
        public bool IsPalindrome(string s, int i ,int j)
        {
            while (i < j)
            {
                if (s[i++] != s[j--])
                {
                    return false;
                }
            }
            return true;
        }
    }

    代码展示(C++)

    class Solution {
    public:
        bool validPalindrome(string s) {
            int left = 0;
            int right = s.length() - 1;
            while(left < right){
                if(s[left] == s[right]){
                    left++;
                    right--;
                }
                else{
                    return isPalindrome(s,left,right-1)||isPalindrome(s,left+1,right);
                }
            }
            return true;
        }
        
        bool isPalindrome(string s,int left,int right){
            while(left < right){
                if(s[left++]!=s[right--]){
                    return false;
                }
            }
            return true;
        }
    };

    提交结果

     

  • 相关阅读:
    Cisco 交换机配置的基本命令
    Mysql读写分离方案-Amoeba环境部署记录
    centos7下部署zabbix3.4+grafana
    Docker
    Linux 安装源码软件
    mysql 日志
    mysql导出导入数据
    mysql 数据库的备份和还原
    Mysql 数据库管理
    英语单词
  • 原文地址:https://www.cnblogs.com/KingR/p/12927241.html
Copyright © 2011-2022 走看看