资讯专栏INFORMATION COLUMN

[LeetCode] Reverse String

Karrdy / 1561人阅读

Problem

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

Example

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

Solution

1. Two-Pointer --3ms

public class Solution {
    public String reverseString(String s) {
        char[] str = s.toCharArray();
        int left = 0, right = str.length-1;
        while (left < right) {
            char temp = str[left];
            str[left] = str[right];
            str[right] = temp;
            left++;
            right--;
        }
        return new String(str);
    }
}

2. StringBuilder --5ms

public class Solution {
    public String reverseString(String s) {
        return  new StringBuilder(s).reverse().toString();
    }
}

3. Recursion --22ms

public class Solution {
    public String reverseString(String s) {
        int len = s.length();
        if (len <= 1) return s;
        String leftStr = s.substring(0, len / 2);
        String rightStr = s.substring(len / 2, len);
        return reverseString(rightStr) + reverseString(leftStr);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65992.html

相关文章

  • 翻转字符串的相关题目

    摘要:一题目描述空格分隔,逐个反转二题目描述三题目描述当然也可以用的做,不过用双指针更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 题目描述 Given a string, you need to reverse the order of chara...

    lykops 评论0 收藏0
  • [LeetCode] 557. Reverse Words in a String III

    Problem Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1:Input: Lets take LeetCode contest...

    104828720 评论0 收藏0
  • [Leetcode] Reverse Words in a String 反转单词顺序

    摘要:代码先反转整个数组反转每个单词双指针交换法复杂度时间空间思路这题就是版的做法了,先反转整个数组,再对每个词反转。 Reverse Words in a String Given an input string, reverse the string word by word. For example, Given s = the sky is blue, return blue is...

    codeKK 评论0 收藏0
  • [LeetCode] Reverse Words in a String II

    Problem Reverse Words in a String IIGiven an input string , reverse the string word by word. Example Input: [t,h,e, ,s,k,y, ,i,s, ,b,l,u,e]Output: [b,l,u,e, ,i,s, ,s,k,y, ,t,h,e] Note A word is defin...

    浠ラ箍 评论0 收藏0
  • LeetCode 345. Reverse Vowels of a String

    摘要:描述编写一个函数,以字符串作为输入,反转该字符串中的元音字母。示例输入输出示例输入输出说明元音字母不包含字母。找到所有的元音字母索引,第一个索引对应的元素和最后一个索引对应的元素交换,第二个和倒数第二个交换,第三个和倒数第三个交换。 Description Write a function that takes a string as input and reverse only th...

    archieyang 评论0 收藏0
  • [LeetCode] Reverse Vowels of a String

    摘要:第二种解法相同的思路,一头一尾两个指针向中间夹逼。注意只有当头指针为元音字母时,才会操作尾指针。判断尾指针非元音字母的条件 Problem Write a function that takes a string as input and reverse only the vowels of a string. Example 1:Given s = hello, return hol...

    dabai 评论0 收藏0

发表评论

0条评论

Karrdy

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<