1: class Solution {
2: public:
3: bool isStrobogrammatic(string num) {
4: if (num.size() == 0) return true;
5: int l = 0, r = num.size()-1;
6: while (l < r) {
7: if ((num[l] == '6' && num[r] == '9') || (num[l] == '9' && num[r] == '6') ||
8: (num[l] == num[r] && num[l] == '1') || (num[l] == num[r] && num[l] == '8' ||
9: (num[l] == num[r] && num[l] == '0'))) {
10: l++; r--;
11: } else {
12: return false;
13: }
14: }
15: if (num.size() & 1) return num[l] == '8' || num[l] == '1' || num[l] == '0';
16: return true;
17: }
18: };
Then I read the top rated solution and realized that we can set up a look up table first and the code becomes very concise.
1: class Solution {
2: public:
3: bool isStrobogrammatic(string num) {
4: unordered_map<char, char> dict{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
5: int n = num.length();
6: for (int l = 0, r = n - 1; l <= r; l++, r--)
7: if (dict.find(num[l]) == dict.end() || dict[num[l]] != num[r])
8: return false;
9: return true;
10: }
11: };
No comments:
Post a Comment