Leetcode Strobogrammatic Number

[LeetCode] 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.
Example 1:
  Input: "69"
 Output: true
Example 2:
  Input: "88"
 Output: true 
Example 3:
  Input: "962"
 Output: false 
This question defines a symmetrical number, that is, a number is rotated 180 degrees as the original, that is, it is the same as the reverse, such as 609, the reverse is still 609, etc. There are actually few numbers that satisfy this condition, only 0, 1, 8, 6, 9. This question can actually be regarded as a special case of seeking the number of replies. We still use double pointers to detect, so if the first and last two numbers are equal, then only one of them is 0,1,8, if If they are not equal, one must be 6 and one is 9, or one is 9 and one is 6, and all other cases return false, see the code below;
Solution one:

  Class Solution { 
  Public : 
      Bool isStrobogrammatic( string num) { 
          Int l = 0 , r = num.size() - 1 ; 
          While (l <= r) { 
              If (num[l] == num[r]) { 
                  If (num[l] != ' 1 ' && num[l] != ' 0 ' && num[l] != ' 8 ' ){ 
                      Return false ; 
                  } 
              } else { 
                  If ((num[l] != ' 6 ' || num[r] != ' 9 ' ) && (num[l] != ' 9 ' 
                      || num[r] != ' 6 ' )) { 
                      Return false ; 
                  } 
              } 
              ++l; -- r; 
          } 
          Return true ; 
      } 
  }; 

Since there are not many numbers that satisfy the meaning of the question, we can use the hash table to do all the mappings that match the meaning of the question into the hash table, and then scan the double pointer to see if the two numbers in the corresponding position are hashed. There is a mapping in the table. If it does not exist, it returns false. The traversal completion returns true. See the code as follows:
Solution 2:

  Class Solution { 
  Public : 
      Bool isStrobogrammatic( string num) { 
          Unordered_map < char , char > m {{ ' 0 ' , ' 0 ' }, { ' 1 ' , ' 1 ' }, 
                        { ' 8 ' , ' 8 ' }, { ' 6 ' , ' 9 ' }, { ' 9 ' , ' 6 ' }}; 
          For ( int i = 0 ; i <= num.size() / 2; ++ i) { 
              If (m[num[i]] != num[num.size() - i - 1 ]) return false ; 
          } 
          Return true ; 
      } 
  }; 

Comments

Popular posts from this blog

SOX - Sound eXchange - How to use SOX for audio processing tasks in research.

Sox of Silence - Original post - http://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/

How to get video or audio duration of a file using ffmpeg?