Leetcode-344-Reverse String

superorange 2022/07/10 427Views

leetcode:https://leetcode.com/problems/reverse-string

Desciption:
Write a function that reverses a string. The input string is given as an array of characters s

idea:

step1: set two pointer(start index, end index)

step2: By setting the temporary variable, swap the front and back elements until the middle one is reached

Code:

class Solution {
    public void reverseString(char[] s) {
        int i = 0;
        int j = s.length-1;
        if(j == 0){
            System.out.print("");
        }
        while(i<j){
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }
}