题目

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:

  1. Input: "Hello, my name is John"
  2. Output: 5

题意

计算给定字符串中非空子串的个数

思路

直接遍历处理即可。


代码实现

Java

  1. class Solution {
  2. public int countSegments(String s) {
  3. int count = 0;
  4. int len = 0;
  5. for (char c : s.toCharArray()) {
  6. if (c != ' ') {
  7. len++;
  8. } else {
  9. count += len > 0 ? 1 : 0;
  10. len = 0;
  11. }
  12. }
  13. count += len > 0 ? 1 : 0;
  14. return count;
  15. }
  16. }