434. Number of Segments in a String
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:
Input: "Hello, my name is John" Output: 5
注意审题:一个segment是一段连续的无space的字符串,所以判断字符用空格就够了
public class Solution { public int countSegments(String s) { if(s == null || s.length() == 0) return 0; int count = 0; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ' ' && s.charAt(i - 1) != ' ') count++; } if (s.charAt(s.length() - 1) != ' ') count++; return count; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步