Simple Java solution without recursion


  • 37
    S
    public class Solution {
        public List<String> findStrobogrammatic(int n) {
            List<String> one = Arrays.asList("0", "1", "8"), two = Arrays.asList(""), r = two;
            if(n%2 == 1)
                r = one;
            for(int i=(n%2)+2; i<=n; i+=2){
                List<String> newList = new ArrayList<>();
                for(String str : r){
                    if(i != n)
                        newList.add("0" + str + "0");
                    newList.add("1" + str + "1");
                    newList.add("6" + str + "9");
                    newList.add("8" + str + "8");
                    newList.add("9" + str + "6");
                }
                r = newList;
            }
            return r;   
        }
    
    }

  • 0
    C

    Nice one! A clean iterative solution!


  • 0

    Pretty smart solution.

    C++ version:

    class Solution{
    public:
    vector<string> findStrobogrammatic(int n) {
        if(n <= 0) return {};
        vector<string> A = {"0", "1", "8"};//length = 1
        vector<string> B = {""};//length = 2
        if(n == 1) return A;
        if(n & 1) B = A;
        for(int len = B[0].size(); len < n; len = len + 2){
            vector<string> tmp;
            for(auto str : B){
                if(len + 2 < n){ string s0 = '0' + str + '0'; tmp.push_back(s0);}
                string s1 = '1' + str + '1'; tmp.push_back(s1);
                string s2 = '6' + str + '9'; tmp.push_back(s2);
                string s3 = '8' + str + '8'; tmp.push_back(s3);
                string s4 = '9' + str + '6'; tmp.push_back(s4);
            }
            B = tmp;
        }
        return B;
    }
    };

Log in to reply
 

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