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"]
// 기능 목록 정의
// 스택을 생성한다
// 스택에 배열의 요소를 추가한다
// 스택의 가장 최근 추가된 데이터를 pop
class Solution {
public void reverseString(char[] s) {
Stack<Character> stack = new Stack();
for (char element : s) {
stack.push(element);
}
for (int i = 0; i < s.length; i++) {
s[i] = stack.remove(stack.size() - 1);
}
System.out.println(s);
}
}
public class Solution {
public String reverseString(String s) {
char[] word = s.toCharArray();
int i = 0;
int j = s.length() - 1;
while (i < j) {
char temp = word[i];
word[i] = word[j];
word[j] = temp;
i++;
j--;
}
return new String(word);
}
class Solution(object):
def reverseString(self, s):
l = len(s)
if l < 2:
return s
return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2])
class SolutionClassic(object):
def reverseString(self, s):
r = list(s)
i, j = 0, len(r) - 1
while i < j:
r[i], r[j] = r[j], r[i]
i += 1
j -= 1
return "".join(r)
class SolutionPythonic(object):
def reverseString(self, s):
return s[::-1]