LeetCode [434] the number of words in a string

Topic:
the number of words in a string of statistics, the word here refers to the continuous character is not a space.

Note that you can assume that the string was does not include any non-printable characters.

Example:

Enter: "Hello, my name is John "
Output: 5

	public int countSegments(String s) {
        String str = s.trim();
        if(str.length() == 0)
            return 0;
        int ans = 0;
        for(int i=0;i<str.length();i++){
            //非空直接跳过去,只有空串+1
            if(isEmpty(str.charAt(i))){
                ans++;
                //将连续空格跳过去
                while(i!=str.length() && isEmpty(str.charAt(i)))
                    i++;
            }
        }
        return ans +1;
    }
    public  boolean isEmpty(char c ){
        return c==' ';
    }
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/103744039