LeetCode刷题记录10——434. Number of Segments in a String(easy)

LeetCode刷题记录10——434. Number of Segments in a String(easy)

目录

LeetCode刷题记录9——434. Number of Segments in a String(easy)

题目

语言

思路

源码

后记


题目

LeetCode刷题记录10——434. Number of Segments in a String(easy)

题目的输入是一个字符串s,输出是一个int型的整数。计算过程为:输出由空白字符切割出的片段数,如图所示,这个片段数为:Hello, my name is John这五个片段。特别要注意的是第一个不是Hello而是Hello,

语言

Java

LeetCode刷题记录10——434. Number of Segments in a String(easy)

思路

分析:这题不能只是找单词这么简单,因为它也可以有逗号,他是要找到由空格分开的,多少个空格都行,只要是空格把你们分开的,那不管是逗号还是字母,都算一个。

所以我先把字符串s转换为字符数组str,接着遍历字符数组,当碰到空格就返回循环继续;如果不是空格了,那就count计数器加加,显然可以看出,这里碰到一个字母就会加加,所以还得用个循环,把其余的字母“跳过”,找到下一个空格,最后返回count的值。

源码

class Solution {
    public int countSegments(String s) {
        int count = 0;
        char str[]=s.toCharArray();
        for (int i=0;i<str.length;i++) {
            if (str[i]==' ') 
                continue;
            count++;
            while (i<str.length&& str[i]!=' ') 
                i++;
        }
        return count;
    }
}

后记

因为笔者最近在上java的课程,所以大多用的是java语言,后期准备去学习C++,用C++来写。