Number of Segments in a String
Posted amazingzoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
1 public class Solution { 2 public int countSegments(String s) { 3 int result = 0; 4 5 int i = 0, n = s.length(); 6 while (i < n) { 7 if (s.charAt(i) != ‘ ‘) { 8 while (i < n && s.charAt(i) != ‘ ‘) i++; 9 result++; 10 } 11 12 while (i < n && s.charAt(i) == ‘ ‘) i++; 13 } 14 return result; 15 } 16 }
以上是关于Number of Segments in a String的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 434. 字符串中的单词数(Number of Segments in a String)
Number of Segments in a String
434. Number of Segments in a String
434. Number of Segments in a String