zoukankan      html  css  js  c++  java
  • 力扣题解-680. 验证回文字符串II

    题目描述

    给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

    示例 1:

    输入: "aba"
    输出: True

    示例 2:

    输入: "abca"
    输出: True
    解释: 你可以删除c字符。

    注意:

    字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。

    1、思路
    在判断字符串是否是回文串的时候用两个指针,一个从头开始扫,一个从后面开始扫,如果两个指针的值不等那么就不是回文串。如果相等继续比较。
    这个题也可以用这种方式。但是在遇到不同的时候有两种解决方法:1、删除前面的字符,2、删除后面的字符,然后继续比较。如果出现不等的那么就不行。

    2、代码

    class Solution {
        public boolean validPalindrome(String s) {
            int head = 0;
            int tail = s.length()-1;
            boolean res = true;
            while(head <= tail){
                if(s.charAt(head) == s.charAt(tail)){
                    head++;
                    tail--;
                    continue;
                }else{
                    int h = head+1;
                    int t = tail;
                    boolean f = true;
                    while(h <= t){
                        if(s.charAt(h) != s.charAt(t)){
                            f = false;
                            break;
                        }else{
                            h++;
                            t--;
                        }
                    }
                    boolean f1 = true;
                    int h1 = head;
                    int t1 = tail-1;
                    while(h1 <= t1){
                        if(s.charAt(h1) != s.charAt(t1)){
                            f1 = false;
                            break;
                        }else{
                            h1++;
                            t1--;
                        }
                    }
                    return f || f1 ;
                }
               
            }
            return res;
    
        }
    }
    
  • 相关阅读:
    SPLAY,LCT学习笔记(五)
    SPLAY,LCT学习笔记(四)
    SPLAY,LCT学习笔记(三)
    NOI 2012 随机数生成器
    SPLAY,LCT学习笔记(二)
    SPLAY,LCT学习笔记(一)
    bzoj 1503 郁闷的出纳员
    bzoj 1112 poi 2008 砖块
    bzoj 1064 noi2008 假面舞会题解
    数论知识点总结(noip范围)
  • 原文地址:https://www.cnblogs.com/Z-Dey/p/12920069.html
Copyright © 2011-2022 走看看