Java state machine


  • 0
    F

    public class Solution {

    private enum State {
        SPACE, SEGMENT
    } 
    
    public int countSegments(String s) {
        if(s == null) {
            return 0;
        }
        
        int ctr = 0;
        int loc = 0;
        
        State state = State.SPACE; 
        
        while(loc < s.length()) {
            if(s.charAt(loc) != ' ') {
                if(state == State.SPACE) {
                    ctr++;
                }
                
                state = State.SEGMENT;
            } else {
                state = State.SPACE;
            }
            
            loc++;
        }
        
        return ctr;
    }
    

    }


Log in to reply
 

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