diff --git a/README.md b/README.md index 14bdc35..23aaf3c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ | Current Status| Stats | | :------------: | :----------: | -| Total Problems | 185 | +| Total Problems | 186 | @@ -269,3 +269,7 @@ pattern = "abba", str = "dog dog dog dog" should return false.| [word_pattern.cp price of a stock on ith day. If you are permitted to only complete one transaction per day (i.e buy one and sell one stock), design an algorithm to find the maximum profit.| [best_time_to_buy_sell.cpp](leet_code_problems/best_time_to_buy_sell.cpp)| +| Given a sentence, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.| + Example: + Input: She loves chocolate + Output: ehs sevol etalocohc|[reverse_words.cpp](leet_code_problems/reverse_words.cpp)| diff --git a/leet_code_problems/reverse_words.cpp b/leet_code_problems/reverse_words.cpp new file mode 100644 index 0000000..1102a68 --- /dev/null +++ b/leet_code_problems/reverse_words.cpp @@ -0,0 +1,42 @@ +/* + * Given a string, you need to reverse the order of characters in each word within a sentence + * while still preserving whitespace and initial word order. + * + * Example: + * Input: She loves chocolate + * Output: ehs sevol etalocohc + * + * Approach: + * Use two indices to figure out non-whitespace characters, and reverse + * the portion. + */ + +#include +#include + + +std::string reverse_words(std::string& sentence) +{ + for(int i = 0; i < sentence.length(); ++i) { + if (sentence[i] != ' ') { + int j = i; + // let j find the end of non-whitespace portion + while (j < sentence.length() && + sentence[j] != ' ') { + j++; + } + std::reverse(sentence.begin() + i, sentence.begin() + j); + // reset i to next word. + i = j - 1; + } + } + return sentence; +} + +int main() +{ + std::string sentence{"She loves chocolate"}; + std::cout << "Input: " << sentence << std::endl; + std::cout << "Output: " << reverse_words(sentence) << std::endl; + return 0; +} \ No newline at end of file