ID | Title | Difficulty | |
---|---|---|---|
Loading... |
434. Number of Segments in a String
Easy
LeetCode
String
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;
}
}
按 <- 键看上一题!
433. Minimum Genetic Mutation
按 -> 键看下一题!
435. Non-overlapping Intervals