Valid Palindrome
2/20/2018 update
Better not include while within while. Use the original solution.
---------------------------------------------------------
11/30/2017 update
A more concise version is as follows.
Have to add i<j as condition when skip none letter or digit char, otherwise index would out of bound.
------------------------
思路:
这道题主要要熟悉java build-in 对操作string的一些函数。
String.toLowerCase().
Character.isLetterOrDigit().
实现:
先把s转换成lower case,这样不用在循环里面再每个转了。lintcode答案是刷题学生自己传上去的,很多不够优化。代码如下:
Better not include while within while. Use the original solution.
---------------------------------------------------------
11/30/2017 update
A more concise version is as follows.
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
while (i<j&&!Character.isLetterOrDigit(s.charAt(i))) i++;
while (i<j&&!Character.isLetterOrDigit(s.charAt(j))) j--;
if (Character.toLowerCase(s.charAt(i))!= Character.toLowerCase(s.charAt(j)))
{
return false;
}
i++;
j--;
}
return true; }
}
Have to add i<j as condition when skip none letter or digit char, otherwise index would out of bound.
------------------------
这道题主要要熟悉java build-in 对操作string的一些函数。
String.toLowerCase().
Character.isLetterOrDigit().
实现:
先把s转换成lower case,这样不用在循环里面再每个转了。lintcode答案是刷题学生自己传上去的,很多不够优化。代码如下:
public class Solution {
/*
* @param s: A string
* @return: Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
int left=0;
int right=s.length()-1;
s=s.toLowerCase();
while(left<right)
{
char lc=s.charAt(left);
char rc=s.charAt(right);
if(!Character.isLetterOrDigit(lc))left++;
else if(!Character.isLetterOrDigit(rc))right--;
else if(lc!=rc)
return false;
else{
left++;
right--;
}
}
return true;
}
}
评论
发表评论