[Algorithm] Leetcode_Reverse String

JAsmine_log·2024년 4월 13일
0

Reverse String

Problem

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

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:

  • 1 <= s.length <= 105
  • s[i] is a printable ascii character.

Hint #1

  • The entire logic for reversing a string is based on using the opposite directional two-pointer approach!

Solutions & Analysis

  1. for문으로 index로 처음과 끝의 문자를 점차 교환한다.
  2. left/righ 포인터를 만들어 문제를 교환한다.

Code

Simply

//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/

class Solution {
    public void reverseString(char[] s) {
    	this.s = s;
        int n = s.length;

        for (int i = 0; i < n / 2; i++) {
            char temp = s[i];
            s[i] = s[n - i - 1];
            s[n - i - 1] = temp;
        }
    }
}

Opposite driectional pointer

left, right(stard, end)에 포인트를 둔다
left는 ++, right는 --


class Solution {
    public void reverseString(char[] s) {
    	this.s = s;
        int left = 0;
        int right = s.length - 1;

        while (left <= right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}
profile
Everyday Research & Development

0개의 댓글