码迷,mamicode.com
首页 > 其他好文 > 详细

对palindrome的常用判断

时间:2019-04-20 09:40:26      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:inpu   bool   info   .com   ++   image   rev   else   reverse   

判断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     }

 

对palindrome的常用判断

标签:inpu   bool   info   .com   ++   image   rev   else   reverse   

原文地址:https://www.cnblogs.com/liuliu5151/p/10739807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!