65 lines
1.5 KiB
C++
65 lines
1.5 KiB
C++
// https://leetcode.com/problems/reverse-words-in-a-string/
|
|
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <vector>
|
|
|
|
using namespace std;
|
|
|
|
static string_view findWord(const string& str, size_t &index)
|
|
{
|
|
size_t startIndex, endIndex;
|
|
|
|
// Start of word
|
|
while (index < str.size() && isspace(str[index])) index++;
|
|
startIndex = index;
|
|
|
|
// Last letter
|
|
while (index < str.size() && !isspace(str[index])) index++;
|
|
endIndex = index;
|
|
|
|
return string_view(str.c_str() + startIndex, endIndex - startIndex);
|
|
|
|
}
|
|
|
|
class Solution {
|
|
public:
|
|
string reverseWords(string s) {
|
|
vector<string_view> words;
|
|
size_t index = 0;
|
|
do
|
|
{
|
|
string_view sv = findWord(s, index);
|
|
if (!sv.empty())
|
|
{
|
|
words.push_back(sv);
|
|
}
|
|
} while (index < s.size());
|
|
|
|
string toRet;
|
|
toRet.reserve(s.size());
|
|
|
|
for (auto iter = words.crbegin(); iter != words.crend(); iter++)
|
|
{
|
|
toRet += *iter;
|
|
toRet += " ";
|
|
}
|
|
toRet.resize(toRet.size() - 1);
|
|
|
|
return toRet;
|
|
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
Solution s;
|
|
cout << s.reverseWords("the sky is blue") << endl;
|
|
cout << s.reverseWords(" hello world ") << endl;
|
|
cout << s.reverseWords("a good example") << endl;
|
|
cout << s.reverseWords(" Bob Loves Alice ") << endl;
|
|
}
|
|
|