2021.10.07 - 116.字符串中的单词数

1. 题目

在这里插入图片描述

2. 思路

(1) 模拟法

  • 先将指针right指向单词第一个字母的位置,再将指针left指向该位置,然后right向后移动到单词后第一个空格的位置,如果此时left<right,则表示两个指针之间包含了一个单词。
  • 为了方便统计最后一个单词,可以先在字符串后面拼接一个空格。

(2) 模拟法优化

  • 其实只需要统计各个单词首字母的个数即可,单词首字母要么是第一个字符,要么其前一个字符是空格。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public int countSegments(String s) {
    
    
        s = s + " ";
        int res = 0;
        int left = 0;
        int right = 0;
        while (left < s.length()) {
    
    
            while (right < s.length() && s.charAt(right) == ' ') {
    
    
                right++;
            }
            left = right;
            while (right < s.length() && s.charAt(right) != ' ') {
    
    
                right++;
            }
            if (left < right) {
    
    
                res++;
            }
        }
        return res;
    }
}

class Solution1 {
    
    
    public int countSegments(String s) {
    
    
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
    
    
            if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
    
    
                res++;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120632552