Sharing my C++ solution


  • 0
    T
    class Solution {
    private:
        bool greaterStringHelper(string& s1, string& s2, int i1, int i2)
        {
            if(i1==s1.length() && i2==s2.length())
                return true;
            else if(i1==s1.length() && i2<s2.length())
                return false;
            else if(i1<s1.length() && i2==s2.length())
                return true;
            else if(s1[i1]>s2[i2])
                return true;
            else if(s1[i1]<s2[i2])
                return false;
            else
                return greaterStringHelper(s1, s2, i1+1, i2+1);
        }
        
        bool greaterString(string& s1, string& s2)
        {
            if(s1.length()>s2.length())
                return true;
            else if(s1.length()<s2.length())
                return false;
            else
                return greaterStringHelper(s1, s2, 0, 0);
        }
        
        void strobogrammaticInRangeHelper(string s, int& result, string low, string high)
        {
            if(s.length()>0 && (s.length()==1 || s[0]!='0') && greaterString(s, low) && greaterString(high, s))
            {
                result++;
            }
            
            if(s.length()>=high.length())
                return;
                
            string temp = '0' + s + '0';
            int last = temp.length()-1;
            strobogrammaticInRangeHelper(temp, result, low, high);
            
            temp[0] = '1';
            temp[last] = '1';
            strobogrammaticInRangeHelper(temp, result, low, high);
            
            temp[0] = '8';
            temp[last] = '8';
            strobogrammaticInRangeHelper(temp, result, low, high);
            
            temp[0] = '6';
            temp[last] = '9';
            strobogrammaticInRangeHelper(temp, result, low, high);
            
            temp[0] = '9';
            temp[last] = '6';
            strobogrammaticInRangeHelper(temp, result, low, high);
        }
        
    public:
        int strobogrammaticInRange(string low, string high) {
            int result = 0;
            string s;
            
            s = "";
            strobogrammaticInRangeHelper(s, result, low, high);
            s = "0";
            strobogrammaticInRangeHelper(s, result, low, high);
            s = "1";
            strobogrammaticInRangeHelper(s, result, low, high);
            s = "8";
            strobogrammaticInRangeHelper(s, result, low, high);
            
            return result;
        }
    };

Log in to reply
 

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