Problem
Write a function that takes a string as input and returns the string reversed.
ExampleGiven s = "hello", return "olleh".
Solution1. 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...
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...
摘要:代码先反转整个数组反转每个单词双指针交换法复杂度时间空间思路这题就是版的做法了,先反转整个数组,再对每个词反转。 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...
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...
摘要:描述编写一个函数,以字符串作为输入,反转该字符串中的元音字母。示例输入输出示例输入输出说明元音字母不包含字母。找到所有的元音字母索引,第一个索引对应的元素和最后一个索引对应的元素交换,第二个和倒数第二个交换,第三个和倒数第三个交换。 Description Write a function that takes a string as input and reverse only th...
摘要:第二种解法相同的思路,一头一尾两个指针向中间夹逼。注意只有当头指针为元音字母时,才会操作尾指针。判断尾指针非元音字母的条件 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...
阅读 3257·2021-09-22 15:54
阅读 2114·2019-08-30 15:53
阅读 2517·2019-08-29 16:33
阅读 1610·2019-08-29 12:29
阅读 1587·2019-08-26 11:41
阅读 2636·2019-08-26 11:34
阅读 3256·2019-08-23 16:12
阅读 1587·2019-08-23 15:56