Leetcode LeetCode algorithm punch card learning day 6

Start with string-related questions

One, reverse the string

Write a function whose role is to reverse the input string. The input string is given in the form of 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.
Insert picture description here
Method one: mine

class Solution {
    
    
    public void reverseString(char[] s) {
    
    
        int length=s.length;
        for(int i=0;i<length/2;i++){
    
    
            char temp=s[i];
            s[i]=s[length-i-1];
            s[length-i-1]=temp;
        }
    }
}

Method two: official, dual pointer

class Solution {
    
    
    public void reverseString(char[] s) {
    
    
        int n = s.length;
        for (int left = 0, right = n - 1; left < right; ++left, --right) {
    
    
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
        }
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reverse-string/solution/fan-zhuan-zi-fu-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/Shadownow/article/details/113728481