【LeetCode】344. Reverse String

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

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

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

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

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

 

Example 1:spa

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

Example 2:code

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

Intuition

use a pointerhtm

 

Solution

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

  

Complexity

Time complexity : O(n)
blog

Space complexity : O(1)ip

 

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索