Java, scan to the middle from ends.


  • 0
    J

    Scan from the ends and check the valid pairs. If odd length, the middle number has to be 0, 1, or 8.

    public class Solution {
    public boolean isStrobogrammatic(String num) {
        int len = num.length();
        int i = 0, j = len - 1;
        boolean isStrob = true;
        while (i < j) {
            if (num.charAt(i) == '0') {
        		if (num.charAt(len - i - 1) != '0') {
        			isStrob = false; 
        			break;
        		}
        	} else 	if (num.charAt(i) == '1') {
        		if (num.charAt(len - i - 1) != '1') {
        			isStrob = false; 
        			break;
        		}
        	} else if (num.charAt(i) == '8') {
        		if (num.charAt(len - i - 1) != '8') {
        			isStrob = false;
        			break;
        		}
        	} else if (num.charAt(i) == '6') {
        		if (num.charAt(len - i - 1) != '9') {
        			isStrob = false;
        			break;
        		}
         	} else if (num.charAt(i) == '9') {
        		if (num.charAt(len - i - 1) != '6') {
        			isStrob = false;
        			break;
        		}
         	} else {
         		isStrob = false;
         		break;
         	}
        	i++;
        	j--;
        }
        if (i == j) { //odd length.
        	if (num.charAt(i) != '1' && num.charAt(i) != '8' && num.charAt(i) != '0')
        		isStrob = false;
        }
        return isStrob;
    }
    

    }


Log in to reply
 

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