Sunday, January 1, 2017

434. Number of Segments in a String

Q:
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:


Input: "Hello, my name is John"
Output: 5
A:


public class Solution {
    public int countSegments(String s) {
        // if s contains only emptySpace
        s = s.trim();
        if(s.length()==0)
            return 0;
        int res =0, pre =-1;
        while(true){
            int i = s.indexOf(' ',pre+1);
            if(i<0)
                break;
            if(i==pre+1){// adjacent space
                pre++;
            }else{
                res++;
                pre = i;
            }
        }
        return res+1;
    }
}
Errors

要记得先trim()


No comments:

Post a Comment