LeetCode434. Number of Segments
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.
思路:
- 找到转换点(前一个是空格,后一个是字母)
- 处理边界问题
代码(自己写的 好开心)
public class Solution {
public int countSegments(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int len = s.length();
int res = 0;
int index = 1;
if (s.charAt(0) != ' ') {
res++;
}
while(index < len-1) {
if(s.charAt(index) == ' ' && s.charAt(index+1) != ' ') {
res++;
}
index++;
}
return res;
}
}
本文标题:LeetCode434. Number of Segments
本文链接:https://www.haomeiwen.com/subject/fjdiwttx.html
网友评论