LeetCode344_344. Reverse a String

LeetCode344_344. Reverse a String

1. Description

Write a function that reverses the input string. The input string is given as a character array s.

Don't allocate extra space for another array, you have to modify the input array in-place, using O(1) extra space to solve this problem.

Example 1:

输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]

Example 2:

输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

hint:

1 <= s.length <= 10 to the 5th power
s[i] are all printable characters in the ASCII code table

Two, solution

Method 1: left and right pointer

    //中文版新的题目对输入参数、返回值做了一定的修改,具体如下
    //采用左右指针
    /*
    执行结果:通过
    执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:47.7 MB, 在所有 Java 提交中击败了95.93%的用户
    通过测试用例:477 / 477
     */
    public void reverseString(char[] 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--;
        }
    }

3. Original English version titles and solutions

1. Description of the topic

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

2. Solution

    //方法一:直接将所有的字符反过来追加到StringBuffer中
    //这种方法速度较慢:Your runtime beats 4.87 % of java submissions.
    public String reverseString(String s) {
    
    
        StringBuffer br = new StringBuffer();
        for (int i = s.length() - 1; i >= 0; i--) {
    
    
            br.append(s.charAt(i));
        }
        return br + "";
    }

The reason why it is listed here separately is because the input and return values ​​of the Chinese and English functions have been changed.

LeetCode 257. All Paths of a Binary Tree
LeetCode 258. Add
Bits LeetCode 263. Ugly Numbers
LeetCode 268. Missing Numbers LeetCode
283. Moving Zeros
LeetCode 287. Finding Duplicates
LeetCode 290. Word Rules
LeetCode 292. Nim Game
LeetCode 303. Area Sum Retrieval - Immutable Arrays
LeetCode 326. Powers of 3
LeetCode 342. Powers of 4
LeetCode 344. Reversing a String



Disclaimer:
        The copyright of the topic belongs to the original author. The code and related statements in the article are written by myself based on my understanding. The relevant pictures in the article are screenshots from my own practice and pictures corresponding to related technologies. If you have any objections, please contact to delete them. grateful. Reprint please indicate the source, thank you.


By luoyepiaoxue2014

Station B: https://space.bilibili.com/1523287361 Click to open the link
Weibo: http://weibo.com/luoyepiaoxue2014 Click to open the link

Guess you like

Origin blog.csdn.net/luoyepiaoxue2014/article/details/129882403