问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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种算法的时间复杂度应当均为:  。

最新文章

  1. ul、li分列显示
  2. STL——遍历 删除 set 元素
  3. php中创建和调用webservice接口示例
  4. html特殊字符转义问题(转!)
  5. C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
  6. [转]phonegap 2.9 IOS Xcode 搭建环境
  7. NULL值比较,两个列的合并,列值按条件替换。
  8. Android版的疯狂猜图游戏源码完整版分享
  9. WINFORM 自定义开关按钮控件-
  10. NSString 用法大全。
  11. twisted学习之reactor
  12. 详解 mpls vpn 的实现
  13. PHP中private、public、protected的区别详解
  14. mysql:数据库备份方案
  15. Go语言编程读书笔记:Go channel(1)
  16. IDEA之debug的坑
  17. linux 下shell脚本备份文件
  18. LeetCode(91):解码方法
  19. 工具 - 怎么看微信h5的源码?
  20. Hbase到Solr数据同步及Solr分离实战

热门文章

  1. 没想到 Google 排名第一的编程语言,为什么会这么火?
  2. 使用nvm安装node,运行node报错 node: command not found
  3. Kubernetes的10个基本事实!你知道几个?k8s与Docker又有何不同?
  4. 利用CloudFlare自动DDNS
  5. NameBeta - 多家比价以节省咱的域名注册成本
  6. Java中lambda(λ)表达式的语法
  7. java 手机号码归属地查询
  8. Windows 平台做 Python 开发的最佳组合
  9. python从放弃到放弃
  10. Salt组件之管理对象Target