A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
一刷
two pointer
public class Solution {
public boolean isStrobogrammatic(String num) {
int lo = 0, hi = num.length()-1;
while(lo<hi){
char l = num.charAt(lo);
char r = num.charAt(hi);
if(l == '6'){
if(r!='9') return false;
lo++;
hi--;
}else if(l == '8'){
if(r!='8') return false;
lo++;
hi--;
}else if(l == '9'){
if(r!='6') return false;
lo++;
hi--;
}else if(l == '1'){
if(r!='1') return false;
lo++;
hi--;
}else if(l == '0'){
if(r!='0') return false;
lo++;
hi--;
}
else return false;
}
char l = num.charAt(lo);
if(lo == hi) return l == '1' || l == '8' || l == '0';
return true;
}
}
二刷
短一点
public class Solution {
public boolean isStrobogrammatic(String num) {
String[] stro = {"11", "88", "69", "96", "00"};
Set<String> dict = new HashSet<>(Arrays.asList(stro));
for (int i=0, j=num.length()-1; i <= j; i++, j--){
if(i==j){
if(num.charAt(i)!='1' && num.charAt(i)!='8' && num.charAt(i)!='0') return false;
}else{
if (!dict.contains(num.charAt(i) + "" + num.charAt(j)))
return false;
}
}
return true;
}
}