The number of words in the string
Title description: Count the number of words in a string, where words refer to consecutive characters that are not spaces.
Please note that you can assume that the string does not contain any non-printable characters.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-segments-in-a-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: string traversal
First, if s is null or s is an empty string, then 0 is directly returned.
Otherwise, a statement COUNT recording the number of words is initialized to 0, lastChar recording the initial value of a character space character , then traverse S characters C , process is as follows:
- If c and lastChar are both spaces, it is currently impossible to be a word, skip;
- If the previous character is a space and the current character is not a space, the current character is the beginning of a word, count plus one, and the lastChar is updated to the current character;
- If neither the previous character nor the current character is a space, skip it;
- If the previous character is not a space and the current character is a space, the previous character is the last character of the previous word. lastChar to the current character.
Finally, return count is the number of words in the string s.
/**
* @Author: ck
* @Date: 2021/9/29 8:51 下午
*/
public class LeetCode_434 {
public static int countSegments(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
char lastChar = ' ';
for (char c : s.toCharArray()) {
if (lastChar == ' ' && c == ' ') {
// 如果上一个字符和当前字符都是空格,则跳过
continue;
} else if (lastChar == ' ' && c != ' ') {
// 如果上一个字符是空格,当前字符不是空格,则当前字符是一个单词的开始,count加一,并且将lastChar更新为当前字符
lastChar = c;
count++;
} else if (lastChar != ' ' && c != ' ') {
// 如果上一个字符和当前字符都不是空格,则跳过
continue;
} else if (lastChar != ' ' && c == ' ') {
// 如果上一个字符不是空格,而当前字符是空格,则上一个字符是上一个单词的最后一个字符。将lastChar更新为当前字符
lastChar = c;
}
}
return count;
}
public static void main(String[] args) {
// 期望输出: 5
System.out.println(countSegments("Of all the gin joints in all the towns in all the world, "));
}
}
[Daily Message] , the difficulty is persistence, and the success is persistence.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。