BiruLyu
7/1/2017 - 2:57 AM

434. Number of Segments in a String.java

public class Solution {
    public int countSegments(String s) {
        if (s == null || s.length() < 1) return 0;
        int res = 0;
        int len = s.length();
        
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                res++;
            }
        }
        return res;

    }
}

/*
"Hello, my name is John"
"apple    "
"    apple"
*/