您的位置:首页 > 其它

LeetCode Strobogrammatic Number

2016-03-05 02:33 267 查看
原题链接在这里:https://leetcode.com/problems/strobogrammatic-number/

题目:

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.

题解:

把几种对应关系加到HashMap中,两个指针向中间夹逼.

Time Complexity: O(n). Space: O(1).

AC Java:

public class Solution {
public boolean isStrobogrammatic(String num) {
HashMap<Character, Character> hm = new HashMap<Character, Character>();
hm.put('6','9');
hm.put('9','6');
hm.put('1','1');
hm.put('0','0');
hm.put('8','8');

int l = 0;
int r = num.length() - 1;
while(l <= r){
if(!hm.containsKey(num.charAt(l))){
return false;
}else if(hm.get(num.charAt(l)) != num.charAt(r)){
return false;
}else{
l++;
r--;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: