AC clean Java recursion solution


  • 4
    public class Solution {
        public boolean isStrobogrammatic(String num) {
            if (num == null) 
                return false;
                
            return helper(num, 0, num.length() - 1);
        }
        
        boolean helper(String num, int lo, int hi) {
            if (lo > hi) 
                return true;
            
            char c1 = num.charAt(lo), c2 = num.charAt(hi);
            
            int mul = (c1 - '0') * (c2 - '0');
            
            if (mul == 1 || mul == 64 || mul == 54 || (mul == 0 && c1 == c2))
                return helper(num, lo + 1, hi - 1);
            else
                return false;
        }
    }

  • 1

    Well, your code has a different idea, without using a look-up table (that part is somewhat uneleglant) and just checking for possible multiplication.


  • 0
    R

    @jeantimex
    This solution is based on CFG

    T ->  6 T 9  | 9 T 6 | 8 T 8 | 1 T 1 | 0 T 0 | 0 | 1 | 8
    

    which T is variable, {0, 1, 8, 6, 9} is a set of terminal symbol.

    Using mult. shorten the code, right?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.