返回

LeetCode之字符串单词计数:技术探索与解题思路

前端

LeetCode是一家备受程序员推崇的编程学习平台,旨在通过趣味且具有挑战性的编程题目来提升用户的编程技能和知识水平。其中,字符串中的单词数便是该平台上的一道经典题目,它考验了用户对字符串处理的掌握程度。本篇文章将对这道题进行深入解析,并提供多种语言的解题思路和示例代码,帮助您轻松掌握字符串处理技巧。

题目

给定一个字符串s,统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。请注意,你可以假定字符串中不包含任何前导或尾随空格。

解题思路

解决LeetCode字符串中的单词数问题的关键在于如何正确地识别单词。由于题目的要求是统计单词的个数,那么首先需要明确单词的定义:单词由连续的不是空格的字符组成。基于此定义,我们可以采用以下两种解题思路:

  1. 分割字符串 :将给定的字符串以空格作为分隔符进行分割,分割后的结果为一个字符串列表,其中每个字符串元素对应一个单词。随后,我们可以统计字符串列表的长度,即可得到字符串中单词的个数。

  2. 遍历字符串 :从左到右遍历字符串,遇到非空格字符时开始计数,遇到空格字符时结束计数。累加计数器即可得到字符串中单词的个数。

示例代码

为了帮助您更好地理解解题思路,我们提供了多种语言的示例代码供您参考:

Python

def word_count(string):
  # 将字符串以空格作为分隔符进行分割
  words = string.split()
  # 返回分割后字符串列表的长度
  return len(words)


# 测试用例
test_string = "Hello, world! This is a test string."
print(word_count(test_string))  # 输出:6

Java

public class WordCount {

    public static int wordCount(String string) {
        // 将字符串以空格作为分隔符进行分割
        String[] words = string.split(" ");
        // 返回分割后字符串数组的长度
        return words.length;
    }

    public static void main(String[] args) {
        // 测试用例
        String testString = "Hello, world! This is a test string.";
        System.out.println(wordCount(testString));  // 输出:6
    }
}

C++

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int wordCount(string string) {
  // 使用字符串流来分割字符串
  stringstream ss(string);
  string word;
  int count = 0;

  // 逐个提取单词
  while (ss >> word) {
    count++;
  }

  return count;
}

int main() {
  // 测试用例
  string testString = "Hello, world! This is a test string.";
  cout << wordCount(testString) << endl;  // 输出:6

  return 0;
}

总结

通过对LeetCode字符串中的单词数难题的解析,我们学习了两种常见的解题思路:分割字符串和遍历字符串。同时,我们还提供了多种语言的示例代码供您参考。希望通过本篇文章的讲解,能够帮助您更好地理解字符串处理技巧,并为解决类似的编程问题打下坚实的基础。