編寫一個函數,其做用是將輸入的字符串反轉過來。輸入字符串以字符數組 char[]
的形式給出。數組
不要給另外的數組分配額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。函數
你能夠假設數組中的全部字符都是 ASCII 碼錶中的可打印字符。spa
示例 1:code
輸入:["h","e","l","l","o"] 輸出:["o","l","l","e","h"]
示例 2:blog
輸入:["H","a","n","n","a","h"] 輸出:["h","a","n","n","a","H"]
分析,這個題目的要求是空間複雜度是O(1),也就是隻能用一個暫存變量來回轉換。
public void reverseString(char[] s) { int i = 0; int j = s.length - 1; while(i<j){ char temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } }