【Leetcode】:344.Reverse String問題in JAVA
Write a function that takes a string as input and returns the string reversed.
Example: Given s = "hello", return "olleh".
この問題は簡単ですが、私が書いた最初のバージョンは意外にもタイムアウトして、合格しませんでした.次のバージョンは通過できます.
Stringとcharの変換を復習します.
char data[] = {'a', 'b', 'c'}; String str = new String(data); char[] cha = {'a','b','c'}; String n = String.valueOf(cha);
Example: Given s = "hello", return "olleh".
この問題は簡単ですが、私が書いた最初のバージョンは意外にもタイムアウトして、合格しませんでした.次のバージョンは通過できます.
Stringとcharの変換を復習します.
char data[] = {'a', 'b', 'c'}; String str = new String(data); char[] cha = {'a','b','c'}; String n = String.valueOf(cha);
public class Solution {
public String reverseString(String s) {
char[] chars = new char[s.length()];
int index = 0;
for (int i = s.length() - 1; i >= 0; i--) {
chars[index++] = s.charAt(i);
}
return new String(chars);
}
}