Number of Segments in a String Solutions in C++
Number 434
Difficulty Easy
Acceptance 37.7%
Link LeetCode
Other languages —
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/number-of-segments-in-a-string/description//// Author : liuyubobobo/// Time : 2017-11-04#include <iostream>#include <string>using namespace std;/// Time Complexity: O(len(s))/// Space Complexity: O(1)class Solution {public:int countSegments(string s) {int startIndex = nextChar(s, 0);if(startIndex == s.size())return 0;int res = 0;for(int start = startIndex, i = start + 1; i <= s.size() ;){if(i >= s.size() || s[i] == ' '){res ++;start = nextChar(s, i);i = start + 1;}elsei ++;}return res;}private:int nextChar(const string& s, int index){if(index >= s.size())return index;while(s[index] == ' ')index ++;return index;}};int main() {cout << Solution().countSegments("Hello, my name is John") << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/number-of-segments-in-a-string/description//// Author : liuyubobobo/// Time : 2017-11-04#include <iostream>#include <string>#include <sstream>using namespace std;/// Special for C++/// Using sstream////// Time Complexity: O(len(s))/// Space Complexity: O(len(s))class Solution {public:int countSegments(string s) {stringstream ss(s);string str;int res = 0;while(ss >> str)res ++;return res;}};int main() {cout << Solution().countSegments("Hello, my name is John") << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/number-of-segments-in-a-string/description//// Author : liuyubobobo/// Time : 2017-11-04#include <iostream>#include <string>#include <sstream>using namespace std;/// Just count the segment number////// Time Complexity: O(len(s))/// Space Complexity: O(1)class Solution {public:int countSegments(string s) {int startIndex = 0;while(startIndex < s.size() && s[startIndex] == ' ')startIndex ++;int res = 0;for(int i = startIndex + 1 ; i <= s.size() ; i ++)if((i == s.size() && s[i-1] != ' ') ||s[i] != ' ' && s[i-1] == ' ')res ++;return res;}};int main() {cout << Solution().countSegments("Hello, my name is John") << endl;return 0;}