557. Reverse Words in a String III
1. Description
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.
2. Example
Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
3. Note
In the string, each word is separated by single space and there will not be any extra space in the string.
4. Solutions
My Accepted Solution
n = i_record.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// string reverseWords(string s)
string reverseWords(string &m_sentence)
{
int wordBeginIndex = 0;
for(int i = 0; i < m_sentence.size(); i++)
{
if(m_sentence[i] == ' ')
{
reverse(m_sentence.begin() + wordBeginIndex, m_sentence.begin() + i);
wordBeginIndex = i + 1;
// it will not reach m_sentence.size(), since the char before belongs to a word rather than blank
}
}
reverse(m_sentence.begin() + wordBeginIndex, m_sentence.end());
return m_sentence;
}
};