LeetCode - Reverse Words in a String III
2022. 7. 16. 22:16ㆍSTUDY/LeetCode
반응형
허잉 ㅜㅜ
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 = "God Ding"
Output: "doG gniD"
Constraints:
- 1 <= s.length <= 5 * 104
- 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.
띄어쓰기를 중심으로 단어를 역순해서 출력한다.
void reverse(char *s, int left, int right) {
char tmp;
while(left < right) {
tmp = s[left];
s[left] = s[right];
s[right] = tmp;
left++;
right--;
}
}
char* reverseWords(char *s) {
int left, right, len = strlen(s);
left = right = 0;
while(1) {
if(right >= len -1) return s;
while(s[left] == ' ') {
// start index of next word
left++;
}
right = left;
while(s[right] != ' ' && right < len) {
// start counting next word's end index.
right++;
}
reverse(s, left, right-1);
left = right;
}
}
728x90
반응형
'STUDY > LeetCode' 카테고리의 다른 글
LeetCode - 733. Flood Fill (0) | 2022.07.17 |
---|---|
LeetCode - 19. Remove Nth Node From End of List (1) | 2022.07.16 |
LeetCode - 876. Middle of the Linked List (0) | 2022.07.16 |
LeetCode 189. Rotate Array (4) | 2022.07.08 |
LeetCode - 704. Binary Search (1) | 2022.07.07 |