Saturday, January 7, 2017

Leetcode -- 434. Number of Segments in a String

434. Number of Segments in a String
  • Difficulty: Easy
https://leetcode.com/problems/number-of-segments-in-a-string/

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
思路: watch 1st char + count segments start with ' ' 

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

No comments:

Post a Comment