当前位置:网站首页>Leetcode advanced path - reverse string

Leetcode advanced path - reverse string

2022-06-10 21:18:00 Li_ XiaoJin

 Write a function , Its function is to invert the input string . Input string as character array  char[]  Given in the form of .

 Do not allocate extra space to another array , You have to modify the input array in place 、 Use  O(1)  To solve this problem .

 You can assume that all characters in an array are  ASCII  Printable characters in code table .


 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"]
  • Double pointer method double pointer method uses two pointers , A left pointer left, Right pointer right, When starting work left Point to first element ,right Point to the tail element . Exchange the elements pointed to by two pointers , And move in the middle , Until the two hands meet .
public class ReverseString {
    public static void reverseString(char[] s) {
        int head = 0;
        int tail = s.length-1;
        
        while (head < tail) {
            char temp = s[head];
            s[head] = s[tail];
            s[tail] = temp;
            head++;
            tail--;
        }
    }

    /**
     *  This is someone else's  
     *  Perform a string reset 
     * @param charArray
     */
    public static void reserve(char[] charArray) {
        int strMin = charArray.length >> 1;
        int start = 0;
        int lasttag = charArray.length-1;
        while (start < strMin) {
            swap(charArray, start, lasttag - start++);
        }
    }

    /**
     *  Swap the positions of two numbers in an array 
     *  The exchange of variables by bits or 
     * @param arr  Arrays that need to be swapped 
     * @param i   The array subscript of the first element to be exchanged 
     * @param j   The array subscript of the second element to be exchanged 
     */
    private static void swap(char[] arr, int i, int j) {
        //  I don't know what it means here , To check ... 
        arr[i] = (char) (arr[i] ^ arr[j]);
        arr[j] = (char) (arr[i] ^ arr[j]);
        arr[i] = (char) (arr[i] ^ arr[j]);
    }
    
    
    public static void main(String[] args) {
        char[] s = new char[]{'h','e','l','l','o'};
        reverseString(s);
    }
}

Copyright: use Creative Commons signature 4.0 International license agreement to license Links:https://lixj.fun/archives/2020-09-09-16-17-48

原网站

版权声明
本文为[Li_ XiaoJin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101959595328.html