JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.

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

Code

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