題目:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
翻譯:
寫一個函數,使用字符串作爲輸入,返回它反轉後的結果。
例如,輸入”hello”,返回”olleh”。
分析:
轉爲字符數組後,將第一個字符和最後一個字符對調,第二個字符和倒數第二個對調,以此類推。
Java版代碼(時間複雜度O(n),空間複雜度O(n)):
public class Solution {
public String reverseString(String s) {
char[] chars=s.toCharArray();
int len=chars.length;
char temp;
for(int i=0;i<len/2;i++){
temp=chars[i];
chars[i]=chars[len-1-i];
chars[len-1-i]=temp;
}
return new String(chars);
}
}