Simple Java solution, 5ms, beats 94.10%


  • 0
    J

    public class Solution {
    char [] l = {'0', '1', '6', '8', '9'};
    char [] r = {'0', '1', '9', '8', '6'};
    public List<String> findStrobogrammatic(int n) {
    List<String> list = new ArrayList<>();
    if(n == 0){
    return list;
    }
    char [] buf = new char[n];
    explore(0, n-1, buf, list, n);
    return list;
    }
    private void explore(int left, int right, char[] buf, List<String>list, int total){
    if(right < left){
    if((total % 2 == 1 && buf[total/2] != '6' && buf[total/2] != '9' )|| total % 2 == 0){
    list.add(new String(buf));
    }
    return;
    }
    for(int i = 0; i < 5; i++){
    if(left == 0 && i == 0 && total > 1) continue; // avoid "00", "000"
    buf[left] = l[i];
    buf[right] = r[i];
    explore(left+1, right-1, buf, list, total);
    }
    }
    }


Log in to reply
 

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