Simple state machine solution


  • 0
    P
    public int countSegments(String s) {
        int state = 1;
        int wordCount = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ' || s.charAt(i) == '\n' || s.charAt(i) == '\t') {
                state = 1;
            } else if (state == 1) {
                wordCount++;
                state = 0;
            }
        }
        return wordCount;
    }

Log in to reply
 

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