Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

 

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

这道题我们可以用双指针去做,左指针放到字符串的第一个字母的位置上,右指针放在了最后的一个指针的位置上面,然后两个指针指向的字母相互交换位置,随后指针移动
代码如下:
void swap(char *a, char* b)
{
    char temp;
    
    temp = *a;
    
    *a = *b;
    
    *b = temp;
    
}

void reverseString(char* s, int sSize){
     char *left = s;
     char* right = s + sSize - 1;
    
     while(left < right)           //满足的判定条件
     {
         swap(left, right);     //交换指针所指向的字符的位置
         left++;                //左边的指针加一
         right--;               //右边的指针减一
         
     }
    
     
}

 

 
posted on 2020-06-16 04:49  闲云潭影  阅读(138)  评论(0编辑  收藏  举报