题目:
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
链接:https://leetcode.com/problems/number-of-segments-in-a-string/#/description
3/25/2017
1 public class Solution { 2 public int countSegments(String s) { 3 boolean inSegment = false; 4 int count = 0; 5 for (int i = 0; i < s.length(); i++) { 6 if (s.charAt(i) == ' ') { 7 if (inSegment) inSegment = false; 8 } else { 9 if (!inSegment) { 10 inSegment = true; 11 count++; 12 } 13 } 14 } 15 return count; 16 } 17 }
别人的精简版
1 public int countSegments(String s) { 2 int res=0; 3 for(int i=0; i<s.length(); i++) 4 if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' ')) 5 res++; 6 return res; 7 }