not so clean but faster java solution


  • 0

    not so clean means i was shocked by this solution: https://discuss.leetcode.com/topic/70642/clean-java-solution-o-n

    however, my solution takes 2ms and beats 100% java solutions(till 2016-12-04)

    anyway, here it is:

    public class Solution {
        public int countSegments(String s) {
            if (s == null) return 0;
            int result = 0, position = 0;
            while (position < s.length() && s.charAt(position) == ' ') position++;
            while (position < s.length()) {
                result++;
                if ((position = s.indexOf(' ', position)) == -1) return result;
                while (position < s.length() && s.charAt(position) == ' ') position++;
            }
            return result;
        }
    }
    

Log in to reply
 

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