Reverse Words in a String III
LeetCode 557 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
- `1 <= s.length <= 5 * 10^4`
- `s` contains printable **ASCII** characters.
- `s` does not contain any leading or trailing spaces.
- There is **at least one** word in `s`.
- All the words in `s` are separated by a single space.
Topics: Two Pointers, String
Approachβ
Direct Approachβ
This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.
When to use
Basic problems that test fundamental programming skills.
Solutionsβ
Solution 1: C# (Best: 544 ms)β
| Metric | Value |
|---|---|
| Runtime | 544 ms |
| Memory | N/A |
| Date | 2018-04-04 |
Solution
public class Solution {
public string ReverseWords(string s) {
char[] sArray = s.ToCharArray();
int n = s.Length;
//reverse(sArray, 0, n-1);
int i=0;int j=0;
while(i<n && sArray[i]==' ') i++;
while(i<n)
{
j=i;
while(j<n && sArray[j]!=' ') j++;
reverse(sArray,i,j-1);
i=j+1;
}
return new string(sArray);
}
void reverse(char[] ar, int l, int r)
{
while (l < r)
{
char temp = ar[l];
ar[l] = ar[r];
ar[r] = temp;
l++;
r--;
}
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Two Pointers | $O(n)$ | $O(1)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.