0%

strobogrammatic-number-i

Strobogrammatic Number – LeetCode 246

Problem

Description

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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool isStrobogrammatic(string num) {
if(!num.size()) return false;
string smap = "01 9 86";
for(int l = 0, r = num.size() - 1; l <= r; ++l, --r){
if(num[r] != smap[num[l]-'0']) return false;
}
return true;
}
};

思路

从头尾两个方向遍历,对可以形成对称结构的字符对应进行查找,依次判断即可。时间复杂度$O(n)$,空间复杂度$O(1)$。

Better

思路

还没看到更好的思路。