leetcode 434. Number of Segments in a String 按照空格分割字符串 + C++的stringstream的一个很好应用示范

谁借莪1个温暖的怀抱¢ 2022-06-04 08:19 251阅读 0赞

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来处理十分的方便

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. class Solution
  20. {
  21. public:
  22. int countSegments(string s)
  23. {
  24. stringstream ss(s);
  25. string tmp = "";
  26. int count = 0;
  27. while (ss >> tmp)
  28. count++;
  29. return count;
  30. }
  31. int countSegmentsByCala(string s)
  32. {
  33. if (s.length() <= 0)
  34. return 0;
  35. int count = 0;
  36. for (int i = 0; i<s.length(); i++)
  37. {
  38. if (s[i] != ' ' && i + 1<s.length() && s[i + 1] == ' ')
  39. count++;
  40. }
  41. return count + (s[s.length() - 1] != ' ');
  42. }
  43. };

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读