A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105sconsists only of printable ASCII characters.
A:
-----------------第三遍--------------------------
class Solution {public: bool isPalindrome(string s) { int i = 0, j = s.length() - 1; while (i < j) { while (i < j && !isalnum(s[i])) { i++; } while (i < j && !isalnum(s[j])) { j--; } if (i < j && tolower(s[i]) != tolower(s[j])) { return false; } else { i++; j--; } } return true; }};
错误:
1: 忘了update i ,j
2: 没有注意是 alphanumeric
3: copy的时候, 把j 直接copy了i,没有发觉。
4: 在对比两个char是否相等的时候,忘了也要确保i<j
-----------------第二遍--------------------------
public class Solution {
public boolean isPalindrome(String s) {
StringBuffer buf = new StringBuffer();
for(int i =0;i<s.length();i++){
char ch = s.charAt(i);
if( (ch>='A'&&ch<='Z' )|| (ch>='a'&&ch<='z')|| (ch>='0'&&ch<='9') )
buf.append(ch);
}
s = buf.toString().toLowerCase();
int i =0,j=s.length()-1;
while(i<j){
if(s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}
-----------------1 st -------------------
public class ValidPalindrome {
public boolean isPalindrome(String s) {
// check empty string or null object
if (s.length() == 0 || s == null) {
return true;
}
int n = s.length();
int i = 0;
int j = n - 1;
char chI, chJ;
while (i <= j) {
// find the
while (i < n && !isAlphanumeric(s.charAt(i))) {
i++;
}
while (j >= 0 && !isAlphanumeric(s.charAt(j))) {
j--;
}
if (i < n && j >= 0) {
chI = s.charAt(i);
chJ = s.charAt(j);
if (chI >= 'A' && chI <= 'Z') {
chI = (char) (chI + 'a' - 'A');
}
if (chJ >= 'A' && chJ <= 'Z') {
chJ = (char) (chJ + 'a' - 'A');
}
if (chI != chJ) {
return false;
}
i++;
j--;
}
}
return true;
}
boolean isAlphanumeric(char ch) {
if (ch >= 'A' && ch <= 'Z')
return true;
if (ch >= 'a' && ch <= 'z')
return true;
if (ch >= '0' && ch <= '9')
return true;
return false;
}
}
Mistakes:
1: 在check 一个string, 是否是palindrome 的时候, 这次,虽然记得update index, 但是,确把后一个j, 给顺手写成了 j++; (跟随前面的i++)
2: 即使是在Eclipse中, 不能随便用 代码完成, 这次, 就给搞出了,自己调用自己的问题了。哎~~~~~~~~ 死循环
4: 没有考虑 “ ” 的情况, 这样,会导致,i,j 越界 !!!!!!!!!!!!
5: alphanumeric characters 是什么意思呢???? 是字母加数字!!!!!!
Learned:
1: char 类型,要加到一个值的时候, 要加个类型转换。
char ch = C; //要转换成lower caes
ch = (char)(ch + ('a' - 'A'));
No comments:
Post a Comment