본문 바로가기

알고리즘과 자료구조/OJ

Leetcode 344. Reverse String

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

 

- Constraints

1. 1 <= s.length <= 10^5

2. s[i] is a printable ascii character

 

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

 

1 ) 투 포인터를 이용해서 스왑

class Solution {
    public void reverseString(char[] s) {
        int l=0,r=s.length-1;
        char temp;
        while(l<r){
            temp=s[l];
            s[l]=s[r];
            s[r]=temp;
            l++;
            r--;
        }
    }
}

 

참고 : 파이썬 알고리즘 인터뷰