My Java O(n) solution.


  • 0
    U
    public class Solution {
    public int countSegments(String s) {
        int count = 0;
        for(int i = 0; i < s.length() ; i++){
            char c = s.charAt(i);
            if(c == ' '){
                if(i > 0 && s.charAt(i - 1) != ' '){
                    count++;
                }
            }
        }
        if(s.length() > 0 && s.charAt(s.length() - 1) != ' '){
            count++;
        }
        return count;
    }
    

    }


Log in to reply
 

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