给定一个字符串,确定它是否是回文,只考虑字母数字字符和忽略情况。
例如,
“一个男人,一个计划,一条运河:巴拿马”是一个回文。
“赛车”不是回文。
注意:
你认为字符串可能是空的吗?在采访中这是一个很好的问题。
为了解决这个问题,我们将空字符串定义为有效的回文。
可以忽略除数字和字母以外的标点符号。
public boolean isPalindrome(String s) {
if (s.length() == 0)
return true;
int i = 0, j = s.length() - 1;
while (i < j) {
while (i < j
&& !((s.charAt(i) >= 'a' && s.charAt(i) <= 'z')
|| (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') || (s
.charAt(i) >= '0' && s.charAt(i) <= '9')))
i++;
while (i < j
&& !((s.charAt(j) >= 'a' && s.charAt(j) <= 'z')
|| (s.charAt(j) >= 'A' && s.charAt(j) <= 'Z') || (s
.charAt(j) >= '0' && s.charAt(j) <= '9'))) {
System.out.println("--" + j);
j--;
}
if (!(s.charAt(i) + "").equalsIgnoreCase(s.charAt(j) + "")) {
return false;
}
i++;
j--;
}
return true;
}
- 1
- 2
- 3
- 4
- 五
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
这样写通过了。下面学习下别人的。
public class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
int front = 0;
int end = s.length() - 1;
while (front < end) {
while (front < s.length() && !isvalid(s.charAt(front))){ // nead to check range of a/b
front++;
}
if (front == s.length()) { // for emtpy string “.,,,”
return true;
}
while (end >= 0 && ! isvalid(s.charAt(end))) { // same here, need to check border of a,b
end--;
}
if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) {
break;
} else {
front++;
end--;
}
}
return end <= front;
}
private boolean isvalid (char c) {
return Character.isLetter(c) || Character.isDigit(c);
}
}
- 1
- 2
- 3
- 4
- 五
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 三十
- 31
- 32
- 33
- 34
- 35
- 36
版权声明:本文为博主转自http://blog.youkuaiyun.com/bug_moving