leetcode -- 125. Valid Palindrome 【有效的回文 + 带条件的双指针】

来源:互联网 发布:淘宝品牌代理加盟 编辑:程序博客网 时间:2024/06/05 03:45

题目

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

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
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.

题意

给定一个字符串,判断它是否是一个回文序列,只考虑字母数字不考虑字符串中的其他情况。

分析及解答

public class Solution { public boolean isPalindrome(String s) {char[] array = s.toLowerCase().toCharArray();int low =0 , high =array.length -1;boolean result = true;while(low < high){boolean isLowLetter = (array[low] >= 97 && array[low] <= 122) || (array[low] >= 48 && array[low] <= 57);boolean isHighLetter = (array[high] >= 97 && array[high] <= 122) ||(array[high] >= 48 && array[high] <= 57);if(isHighLetter && isLowLetter){result = result && (array[low] == array[high]);low ++;high --;}else{if(!isHighLetter){high --;}if(!isLowLetter){low ++;}}}return result;}}



原创粉丝点击