对palindrome的常用判断

判断String是否为palindrome:Two Pointers(left & right) 同时边扫边check 当前两边的char是否相同

对palindrome的常用判断

 

code

 1 public boolean isValidPalindrome(String s){
 2         int l = 0;
 3         int r = s.length() - 1;
 4         while (l < r){
 5             if(s.charAt(l) != s.charAt(r)){
 6                 return false;
 7             }else{
 8                 l++;
 9                 r--;
10             }
11         }
12         return true;
13     }

 

判断number是否为palindrome:先reverse original number 变为reversed number ,再判断 original number == reversed number ?

对palindrome的常用判断

 

 

 

code

 1     public boolean isPalindrome(int x) {
 2         // handle input is negative  like -121 or end with 0 
 3         if (x < 0 || (x != 0 && x % 10 == 0)) return false;
 4 
 5         int temp = x;
 6         int reverseInt = 0;
 7         while (x != 0) {
 8             reverseInt = reverseInt * 10 + x % 10;
 9             x = x / 10;
10         }
11         return (reverseInt == temp);
12     }

 

上一篇:字符串分割为回文串的最小分割次数(palindrome-partitioning-i)


下一篇:LeetCode——Palindrome Number