LintCode Valid Palindrome

准备开始刷题,然后希望把做过的题写在这里,这样既能加深印象,又能有机会找出自己潜在的问题。
题目如下:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

解题代码如下:
思路很简单,就是设置两个指针,一个头一个尾,一直对比到中间,如果遇到不一样就return false。
当然,题目还要求忽略空格和数字,所以这题需要用到Character对象的方法, 这个时间久远不用可能会忘,所以需要认真看一下。

public class Solution {
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
          // Write your code here
          if( s.length() == 0){
          return true;
          }
          int left = 0;
          int right = s.length()-1;
          while(left < right){
                    if(!Character.isLetter(s.charAt(left)) && !Character.isDigit(s.charAt(left))){
                              left++;
                              continue;
                    }
                    if(!Character.isLetter(s.charAt(right)) && !Character.isDigit(s.charAt(right))){
                              right--;
                              continue;
                    }
                    if(Character.toUpperCase(s.charAt(left++)) != Character.toUpperCase(s.charAt(right--))){
                              return false;
                    }
          }
          return true;
          }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,972评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,521评论 0 23
  • 相关DEMO请去我github上下载:网址最近一直在项目改版,所以最近一直没什么时间总结最近遇到的难题!现在给大家...
    芝麻绿豆阅读 1,778评论 11 6
  • 世界很粗糙,时间也不温柔。 我们都是淋透了雨的人,都没有伞。 慌慌张张躲进了屋檐下, 来来往往车水马龙。 想和你一...
    穆颜i阅读 191评论 0 0
  • 元认知能力是指对思考过程的认知与理解。这个概念确实有些抽象,很难理解。但是他又很重要,几乎影响了我们生活工作的方方...
    杨荣鹏阅读 402评论 3 0

友情链接更多精彩内容