​LeetCode刷题实战125:验证回文串

程序IT圈

共 865字,需浏览 2分钟

 · 2020-12-16

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 验证回文串,我们先来看题面:
https://leetcode-cn.com/problems/valid-palindrome/

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.


Note: For the purpose of this problem, we define empty string as valid palindrome.

题意


给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。

样例

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false


解题


首先字符串中多余的字符不在考虑的范围之类,而如果字符串是回文串,我们就可以设置双指针,使用双指针法,一头一尾判断字符是否相等,若存在不相等时输出false。代码如下:

public boolean isPalindrome(String s) {
   if (s.isEmpty())
       return true;

   int begin = 0;
   int end = s.length() - 1;

   char beginChar, endChar;

   while (begin <= end){
       beginChar = s.charAt(begin);
       endChar = s.charAt(end);
       if (!Character.isLetterOrDigit(beginChar)){
           begin++;
           continue;
       }
       else if (!Character.isLetterOrDigit(endChar)){
           end--;
           continue;
       }
       else {
           if (Character.toLowerCase(beginChar) != Character.toLowerCase(endChar))
               return false;
           else{
               begin++;
               end--;
           }
       }
   }

   return true;
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-120题汇总,希望对你有点帮助!
LeetCode刷题实战121:买卖股票的最佳时机
LeetCode刷题实战122:买卖股票的最佳时机 II
LeetCode刷题实战123:买卖股票的最佳时机 III
LeetCode刷题实战124:二叉树中的最大路径和


浏览 16
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报