【Ga】 string-reverse string

topic:

Write a function whose function is to reverse the input string. The input string is given as a character array char [].

Don't allocate extra space to another array, you must modify the input array in place and use O (1) extra space to solve this problem .

You can assume that all characters in the array are printable characters in the ASCII code table.

 

Example 1:

输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-string

answer:

I used parity in the beginning, but then I do n’t think it ’s necessary.

class Solution {
    public void reverseString(char[] s) {
        int len = s.length;
        if (s.length > 0) {
           int center = len / 2;
           for (int i = 0; i < center; i++) {
                   char left = s[i];
                   s [i] = s [len - 1 - i];
                   s[len - 1 - i] = left;
                }
           // 偶数
        //    if (center && 1 == 0) {
        //        for (int i = 0; i < center; i++) {
        //            char left = s[i];
        //            s[i] = s[len - 1 - i];
        //            s[len - 1 -i] = left;
        //        }
        //    } else {
        //         for (int i = 0; i < center; i++) {
        //            char left = s[i];
        //            s[i] = s[len - 1 - i];
        //            s[len - 1 -i] = left;
        //         }
        //    }
        }
    }
}

 

 

 Other people's writing:

for (int i = 0, j = s.length-1; i <= j; i++, j--){
            char a = s[i];
            s[i] = s[j];
            s[j] = a;
        }

Author: zyfsuzy

 

Guess you like

Origin www.cnblogs.com/utomboy/p/12702994.html