Short and Easy Java solution using HashSet


  • 0
    M
    public class Solution {
        public boolean isNumber(String s) {
            s = s.trim();
            int len = s.length();
            if(s == null || len == 0) return false;
            // To keep track of all seen symbols, d: digit
            HashSet<Character> set = new HashSet<Character>();
            boolean checkSign = false;
            for(int i = 0; i < len; i++) {
                // Check if first position in string or next position after e
                if( (checkSign || i == 0) && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
                    checkSign = false;
                }
                else if(s.charAt(i) - '0' >= 0 && s.charAt(i) - '0' < 10) {
                    // Add d: digit to set
                    if(! set.contains('d')) set.add('d');
                    // As seen digit, we dont need to check further sign
                    checkSign = false;
                }
                else if (s.charAt(i) == '.') {
                    // If . is already present in the string return false else add it in set
                    if(set.contains('.')) return false;
                    set.add('.');
                }
                else if(s.charAt(i) == 'e') {
                    // If first character in string is e or already seen e then return false
                    if(! set.contains('d') || set.contains('e')) return false;
                    // Now we cannot have any . or e and we must have digit after e 
                    set.add('.'); set.add('e'); set.remove('d');
                    // Next character might be a sign. Ex: 54e-9
                    checkSign = true;
                }
                else return false;
            }
            // If it contains any digit and a digit after e
            return set.contains('d');
        }
    }

Log in to reply
 

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