问题描述:
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
解释说明:旋转180度后保持一致的几组数是:0和0,1和1,6和9,8和8, 9和6。两个指针从两端逼近,若遇到的不是以上这些组合,当机立断返回false。如果循环能正常结束(循环条件:左指针<=右指针),就返回true
代码如下:
class Solution {
public boolean isStrobogrammatic(String num) {
int left=0;
int right=num.length()-1;
while(left<=right){
if(!(rotationValid(num.charAt(left), num.charAt(right)))) return false;
left++;
right--;
}
return true;
}
private boolean rotationValid(char a, char b){
if((a=='0')&&(b=='0')) return true;
else if((a=='1')&&(b=='1')) return true;
else if((a=='6')&&(b=='9')) return true;
else if((a=='8')&&(b=='8')) return true;
else if((a=='9')&&(b=='6')) return true;
else return false;
}
}
时间复杂度:O(n)