001-反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 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"]
1 public class Solution { 2 public void ReverseString(char[] s) { 3 int left = 0; 4 int i = 0; 5 int right = s.Length - 1; 6 while(left <= (right - i)){ 7 char temp1; 8 char temp2; 9 temp1 = s[left]; 10 temp2 = s[right - i]; 11 s[left] = temp2; 12 s[right - i] =temp1; 13 left++; 14 i++; 15 } 16 } 17 }
优化代码:
1 public class Solution { 2 public void ReverseString(char[] s) { 3 int right = s.Length ; 4 for(int left = 0;left<=(right-1-left);left++){ 5 char temp; 6 temp = s[left]; 7 s[left] = s[right-1-left]; 8 s[right-1-left] = temp; 9 } 10 } 11 }
解题思路总结:
利用双下标解决,我们可以发现下标[i]和下标[length - 1 - i]需要互相调换,这个时候只需要一个中级变量存储其中得一个值即可。(i=0,length=s.Length)