C#LeetCode刷题之#434-字符串中的单词数​​​​​​​(Number of Segments in a String)

C#LeetCode刷题之#434-字符串中的单词数​​​​​​​(Number of Segments in a String)

问题

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

输入: “Hello, my name is John”

输出: 5

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.

Input: “Hello, my name is John”

Output: 5

示例

public class Program {

    public static void Main(string[] args) {
        var s = "Hello, my name is Iori!";
        var res = CountSegments(s);
        Console.WriteLine(res);

        s = "It's mine!";
        res = CountSegments2(s);
        Console.WriteLine(res);

        s = "using System.Collections.Generic;";
        res = CountSegments3(s);
        Console.WriteLine(res);

        s = "Hello, my daughter's name is Cherry!";
        res = CountSegments4(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int CountSegments(string s) {
        var split = s.Split(' ');
        var index = 0;
        foreach(var item in split) {
            if(item.Trim() != "") index++;
        }
        return index;
    }

    private static int CountSegments2(string s) {
        string[] split = s.Split(new char[] { ' ' },
                                 StringSplitOptions.RemoveEmptyEntries);
        return split.Length;
    }

    private static int CountSegments3(string s) {
        var res = 0;
        var notEmpty = false;
        for(var i = 0; i < s.Length; i++) {
            if(s[i] != ' ') notEmpty = true;
            else {
                if(notEmpty) {
                    res++;
                    notEmpty = false;
                }
            }
        }
        if(notEmpty) { res++; }
        return res;
    }

    private static int CountSegments4(string s) {
        var res = 0;
        var preEmpty = true;
        for(var i = 0; i < s.Length; i++) {
            if(preEmpty && s[i] != ' ') res++;
            preEmpty = s[i] == ' ';
        }
        return res;
    }

}

以上给出4种算法实现,以下是这个案例的输出结果:

5
2
2
6

分析:

考虑到部分运行库的使用,以上4种算法的时间复杂度应当均为: O(n)

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3941

(1)
上一篇 2020年06月08日 20:46
下一篇 2020年06月08日 20:50

相关推荐

发表回复

登录后才能评论