Andy Back-end Dev Engineer

ARTS_Week13

2019-07-03

Algorithm

leetcode 344. Reverse String

Description

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

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

You may assume all the characters consist of printable ascii characters.

Example

Input: [“h”,”e”,”l”,”l”,”o”] Output: [“o”,”l”,”l”,”e”,”h”]

Input: [“H”,”a”,”n”,”n”,”a”,”h”] Output: [“h”,”a”,”n”,”n”,”a”,”H”]

Solution

Approach1:

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

Complexity analysis

  • Time complextiy : O(n).
  • Space complexity : O(1).

Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse String. Memory Usage: 47 MB, less than 90.49% of Java online submissions for Reverse String.

Review

Facebook’s Libra Masterplan

Tips

Bash Basic

Share

Follow these steps to solve any Dynamic Programming interview problem


Similar Posts

上一篇 ARTS_Week12

Comments