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

算法的重要性,我就很少说了吧,想去大厂,就必需要通过基础知识和业务逻辑面试+算法面试。因此,为了提升你们的算法能力,这个号后续天天带你们作一道算法题,题目就从LeetCode上面选 !今天和你们聊的问题叫作 验证回文串,咱们先来看题面:https://leetcode-cn.com/problems/valid-palindrome/

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

 

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;
}ide

好了,今天的文章就到这里。

 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

相关文章
相关标签/搜索