344. Reverse String
来源:互联网 发布:企业网络建设需求分析 编辑:程序博客网 时间:2024/06/07 12:44
344. Reverse String
DescriptionHintsSubmissionsSolutions
- Total Accepted: 159393
- Total Submissions: 271454
- Difficulty: Easy
- Contributor: LeetCode
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question.
算法思路
由于测试的数据比较多,一开始想的比较简单,直接利用字符串拼接,没有考虑效率问题,最后结果超时了。
第一种方法是比较简单的方法,直接利用字符串拼接
第二种方法采用末尾和前位交换的方法,但是要注意的是要先把字符串转化为字符数组,因为在交换的过程中不能直接对字符串中的某一字符赋值,
然后返回的时候要new String对象,否则返回的是一个地址
代码一:
public static String reverse(String s){String result = "";for(int j=0; j<s.length(); j++){result = s.charAt(j) + result;}return result;}
代码二:
package easy;public class ReverseString {public static String reverseString(String s) {String string = "";char[] result = s.toCharArray();char temp ; int i = 0; int j = s.length()-1; while(i<j){ temp = result[i]; result[i] = result[j]; result[j] = temp; i++; j--; } return new String(result);}public static void main(String[] args){System.out.println(reverseString("hello"));}}
阅读全文
0 0
- String:344. Reverse String
- 344.Reverse String(String-Easy)
- leetcode--344. Reverse String
- 344. Reverse String
- 344. Reverse String [E]
- LeetCode 344. Reverse String
- 344. Reverse String
- LeetCode 344. Reverse String
- 344. Reverse String
- 344. Reverse String
- 344. Reverse String
- Leetcode:344. Reverse String
- 344. Reverse String
- LeetCode *** 344. Reverse String
- 344. Reverse String
- LeetCode *** 344. Reverse String
- 344. Reverse String
- [leetcode] 344. Reverse String
- 树莓派查找IP
- 选项卡及多个选项卡应用
- Linux日常——进程组、作业、会话
- Linux学习基础篇(六)
- python getattr hasattr setattr delattr函数的使用
- 344. Reverse String
- 面试题24:二叉搜索树的后序遍历序列
- 16. 编写函数,统计一批成绩中各分数段的人数。
- 从前端到后台,开发一个完整功能的小程序
- Android的getSystemService()
- Flink如何应对背压问题
- HDU 2049 不容易系列之(4)——考新郎 (错排公式)
- DataGridView控件---绑定数据的两种方法
- 移动端滑动弹出层页面到底部时,同级兄弟元素也跟着滑动。