本帖最后由 michael_llh 于 2016-12-27 11:42 编辑
Number of Segments in a String
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. Example: Input: "Hello, my name is John" Output: 5
comes from:
题意分析: 这道题其实很简单,就是统计一个字符串当中有几个子字符串,我们只要遍历一次字符串就可以了。
给出参考代码:(C++)
class Solution { public: int countSegments(string s) { int n=0; n = s.length(); char* str= new char(n+1); strcpy(str,s.c_str()); str[n] = '\0'; int i=0; int num = 0; while(str!='\0'){ if(str==' ') num++; i++; } return (num+1); } };
上面的解决办法是比较笨重的,而且会有一些问题,比如在下面这个测试案例上面: 另外的参考解决方法:
方法一: class Solution {public: int countSegments(string s) { istringstream input(s); int count = 0; string tmp; while (getline(input, tmp, ' ')) if (!tmp.empty()) count++; return count; } };
方法二: class Solution { public: int countSegments(string s) { int res = 0; for (int i = 0; i < s.size(); i++) res += s != ' ' && (i + 1 == s.size() || s[i + 1] == ' '); return res; } };
|