Leetcode: Number of Segments in a String

时间:2024-09-03 10:06:32
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

用split()

 public class Solution {
public int countSegments(String s) {
if (s==null || s.length()==0) return 0;
String[] strs = s.split(" ");
int count = 0;
for (String str : strs) {
if (str.length() != 0) count++;
}
return count;
}
}

不用API, better solution, O(N) time O(1) space

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