欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 344. Reverse String--输入字符数组,倒序输出

程序员文章站 2024-03-04 16:49:41
...

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 1:

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

Example 2:

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

 

package com.string;

/**
 * Title:
 *
 * @Author
 * @CreateTime 2019/6/15 15:32
 */
public class Leetcode_344_ReverseString {
    /**
     * for循环写不写均能AC
     * <p>
     * 不写for循环时:
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse String.
     * Memory Usage: 47.7 MB, less than 68.18% of Java online submissions for Reverse String.     * <p>
     * 写for循环时:
     * Runtime: 107 ms, faster than 12.11% of Java online submissions for Reverse String.
     * Memory Usage: 65.5 MB, less than 5.01% of Java online submissions for Reverse String.
     *
     * @param s
     */
    public void reverseString2(char[] s) {
        int i = 0, j = s.length - 1;
        char temp;
        while (i < j) {
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }

        for (int k = 0; k < s.length; k++) {
            if (k == 0) {
                System.out.print("[");
            }
            if (k != s.length - 1) {
                System.out.print("\"" + s[k] + "\",");
            } else {
                System.out.print("\"" + s[k] + "\"]");
            }
        }//for
    }//reverseString


    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse String.
     * Memory Usage: 47.2 MB, less than 68.80% of Java online submissions for Reverse String.
     *
     * @param s
     */
    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;
        }
    }

    public static void main(String[] args) {
        Leetcode_344_ReverseString object = new Leetcode_344_ReverseString();
        object.reverseString(new char[]{'h', 'e', 'l', 'l', 'o'});
    }
}

 

上一篇: LeetCode344-反转字符串

下一篇: