C#LeetCode刷题之#434-字符串中的单词数(Number of Segments in a String)
2024-09-01 04:25:46
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3941 访问。
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
输入: "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
示例
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3941 访问。
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种算法实现,以下是这个案例的输出结果:
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3941 访问。
5
2
2
6
分析:
考虑到部分运行库的使用,以上4种算法的时间复杂度应当均为: 。
最新文章
- ul、li分列显示
- STL——遍历 删除 set 元素
- php中创建和调用webservice接口示例
- html特殊字符转义问题(转!)
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
- [转]phonegap 2.9 IOS Xcode 搭建环境
- NULL值比较,两个列的合并,列值按条件替换。
- Android版的疯狂猜图游戏源码完整版分享
- WINFORM 自定义开关按钮控件-
- NSString 用法大全。
- twisted学习之reactor
- 详解 mpls vpn 的实现
- PHP中private、public、protected的区别详解
- mysql:数据库备份方案
- Go语言编程读书笔记:Go channel(1)
- IDEA之debug的坑
- linux 下shell脚本备份文件
- LeetCode(91):解码方法
- 工具 - 怎么看微信h5的源码?
- Hbase到Solr数据同步及Solr分离实战