Leetcode - Reverse Words in a String (Python)

preview_player
Показать описание
July 2020 Leetcode Challenge
Leetcode - Reverse Words in a String
Рекомендации по теме
Комментарии
Автор

without any built-in functions

result, i, n = '', 0, len(s)
while i<n:
while i<n and s[i] == ' ':i+=1
if i >= n: break
j=i+1
while j<n and s[j]!=' ': j+=1
substring = s[i:j]
if len(result) == 0: result = substring
else: result = substring + ' ' + result
i = j+1
return result

siddharthsingh
Автор

class Solution
{
public:

string removeExtraSpaces(const string &s) {
string result;
bool inword = false;

for (char c : s) {
if (c != ' ') {
result += c;
inword = true;
} else if (inword) {
result += ' ';
inword = false;
}
}


if (!result.empty() && result.back() == ' ') {
result.pop_back();
}

return result;
}

string removeSpaces(const string &s) {
int i = 0, j = s.size() - 1;
while (i < s.size() && s[i] == ' ') {
i++;
}
while (j >= 0 && s[j] == ' ') {
j--;
}
return s.substr(i, j - i + 1);
}


string reverseWords(string s) {

s = removeSpaces(s);

s = removeExtraSpaces(s);

vector<string> tokenized;
stringstream check(s);
string intermediate;


while (getline(check, intermediate, ' ')) {

}

s.clear();

for (int i = tokenized.size() - 1; i >= 0; i--) {
s += tokenized[i];
if (i != 0) {
s += " ";
}
}

return s;
}
}; thats my approach to solve in c++ i used some built in functions but watching yours was pretty shocking as i spent half an hour to crack this 😂 lol

martian
Автор

It's funny how my resolution is different
my code was:
s_sep = s.split()
s_invert = " ".join(s_sep[::-1])
return s_invert
and got the same results!

AdalbertoCarv
visit shbcf.ru