246. Strobogrammatic Number π
Description
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).
Example 1:
Input: num = "69" Output: true
Example 2:
Input: num = "88" Output: true
Example 3:
Input: num = "962" Output: false
Constraints:
1 <= num.length <= 50numconsists of only digits.numdoes not contain any leading zeros except for zero itself.
Solutions
Solution 1: Two Pointers Simulation
We define an array \(d\), where \(d[i]\) represents the number after rotating the digit \(i\) by 180Β°. If \(d[i]\) is \(-1\), it means that the digit \(i\) cannot be rotated 180Β° to get a valid digit.
We define two pointers \(i\) and \(j\), pointing to the left and right ends of the string, respectively. Then we continuously move the pointers towards the center, checking whether \(d[num[i]]\) and \(num[j]\) are equal. If they are not equal, it means that the string is not a strobogrammatic number, and we can directly return \(false\). If \(i > j\), it means that we have traversed the entire string, and we return \(true\).
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 | |