判断String是否为palindrome:Two Pointers(left & right) 同时边扫边check 当前两边的char是否相同
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 ?
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 }
原文地址:https://www.cnblogs.com/liuliu5151/p/10739807.html
时间: 2024-10-22 09:45:30