Java版一:
package tencent;
/**
* 編寫一個函數,其作用是将輸入的字元串反轉過來。輸入字元串以字元數組 char[] 的形式給出。
*
* 不要給另外的數組配置設定額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。
*
* 你可以假設數組中的所有字元都是 ASCII 碼表中的可列印字元。
*
*
*
* 示例 1:
*
* 輸入:["h","e","l","l","o"] 輸出:["o","l","l","e","h"] 示例 2:
*
* 輸入:["H","a","n","n","a","h"] 輸出:["h","a","n","n","a","H"]
*
* 來源:力扣(LeetCode) 連結:https://leetcode-cn.com/problems/reverse-string
* 著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
*
* @author BlueZ
*
*/
public class ReverseString {
public String reverseString(String s) {
System.out.println(s);
return new StringBuffer(s).reverse().toString();
}
public char[] reverseString(char[] s) {
int length = s.length;
for (int j = 0; j < (length + 1) / 2; j++) {
char tmp = s[j];
s[j] = s[length - j - 1];
s[length - j - 1] = tmp;
}
return s;
}
public static void main(String[] args) {
// 解法一
// String result = new ReverseString().reverseString("Hello");
// System.out.println(result);
// 解法二
char[] s = { 'h', 'e', 'l', 'l', 'o', 's' };
System.out.println(new ReverseString().reverseString(s));
}
}