434. Number of Segments in a String

1. Question

You are given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

2. Examples

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

Example 3:

Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

Input: s = ""
Output: 0

3. Constraints

  • 0 <= s.length <= 300
  • s consists of lower-case and upper-case English letters, digits or one of the following characters "!@#$%^&*()_+-=',.:".
  • The only space character in s is ' '.

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
  public int countSegments(String s) {
    int count = 0;
    String[] arr = s.split(" ");
    for (String str : arr) {
      if (!"".equals(str)) {
        count++;
      }
    }
    return count;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""