My Concise Java Solution


  • 7
    S
    public class Solution {
        public boolean isStrobogrammatic(String num) {
            int start = 0;
            int end = num.length() - 1;
            while (start <= end) {
                switch(num.charAt(start)) {
                    case '0':
                    case '1':
                    case '8':
                        if (num.charAt(end) != num.charAt(start)) {
                            return false;
                        }
                        break;
                    case '6':
                        if (num.charAt(end) != '9') {
                            return false;
                        }
                        break;
                    case '9':
                        if (num.charAt(end) != '6') {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
                start++;
                end--;
            }
            return true;
        }
    }

  • 1

    Hi, stevenye. I am not quite familiar with switch statements in Java. Could you please tell me whether case '0', case '1' and case '8' all share the same statements (check for num.charAt(end) != num.charAt(start))?


  • 0
    S

    That's correct. Each case will not end their execution until they meet 'break'.


  • 0

    @stevenye would you please explain why you didn't put if statements for case 0 and case 1?


  • 0

    @shurui Sorry I was wrong. Case 0, 1, 8 are sharing the same case.


  • 0

    @jianchao.li.fighter Because for 0, 1 and 8, their corresponding number at the "mirrored" position should be the same. 0 pairs with 0, 1 pairs with 1, and 8 pairs with 8.


Log in to reply
 

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