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
字符串分割,题意很简单就不说了,就是要注意处理各种极端case
注意直接使用C++的stringstream来处理十分的方便
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int countSegments(string s)
{
stringstream ss(s);
string tmp = "";
int count = 0;
while (ss >> tmp)
count++;
return count;
}
int countSegmentsByCala(string s)
{
if (s.length() <= 0)
return 0;
int count = 0;
for (int i = 0; i<s.length(); i++)
{
if (s[i] != ' ' && i + 1<s.length() && s[i + 1] == ' ')
count++;
}
return count + (s[s.length() - 1] != ' ');
}
};