반응형
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
- 1 <= s.length <= 105
- s[i] is a printable ascii character.
class Solution {
public void reverseString(char[] s) {
for(int i=0; i<s.length/2; i++){
char box = s[i];
s[i] = s[s.length-1-i];
s[s.length-1-i] = box;
}
}
}
557. Reverse Words in a String III
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.
class Solution {
// Approach:
// Using two pointers, 'start' and 'end', each time 'end' reaches a space, we reverse the words before.
// To reverse, we convert the String 's' to a char array, then write a method to reverse the char in the array.
public String reverseWords(String s) {
// Convert s into char array.
char[] chars = s.toCharArray();
int start = 0;
int end;
for (end = 0; end <= chars.length; end++) {
// When 'end' reaches a space character ' ', reverse the words from 'start' to 'end' - 1 index in 'chars'.
if (end == chars.length || chars[end] == ' ') {
reverse(chars, start, end - 1);
// reset the start for the next word.
start = end + 1;
}
}
return new String(chars);
}
// A private method to reverse the char in the array using the 'start' and 'end' pointer.
private void reverse(char[] c, int start, int end) {
while (start < end) {
char tmp = c[end];
c[end] = c[start];
c[start] = tmp;
start++;
end--;
}
}
}
300x250
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] Algorithm I - Day 3 Two Pointers (0) | 2022.10.27 |
---|---|
[LeetCode] Algorithm I - Day 2 Two Pointers (0) | 2022.10.26 |
[LeetCode] Algorithm I - Day 1 Binary Search (0) | 2022.10.26 |
[LeetCode] 371. Sum of Two Integers (두 숫자의 합) (1) | 2022.05.24 |
[LeetCode] 35. Search Insert Position (0) | 2022.04.20 |