first commit

This commit is contained in:
Jose Caban
2025-06-07 11:38:03 -04:00
commit e0316ca3ff
79 changed files with 3155 additions and 0 deletions

View File

@@ -0,0 +1,64 @@
// 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;
}