LeetCode-344:Reverse String
来源:互联网 发布:智慧足迹大数据 编辑:程序博客网 时间:2024/05/21 06:12
原题描述如下:
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
题意
:给定一个字符串,输出它的逆序串。
解题思路:思路1:利用Java里面现有数据结构 StringBuilder的reverse()方法。
思路2:利用栈的后进先出,将该字符串转化为char数组,然后全部压入栈,最后弹出。
思路3:将该字符串转为char数组,然后采用循环,前后对换。
(思路还有很多,大家自行探索)
Java代码:
思路1:public class Solution {
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
}
思路2:
public class Solution {
public String reverseString(String s) {
if(s == null || s.equals("")){
return "";
}
char[] chararr = s.toCharArray();
Stack<String> stack = new Stack<String>();
for(int i=0; i<chararr.length; ++i){
stack.push(chararr[i] + "");
}
StringBuilder builder = new StringBuilder();
while(!stack.isEmpty()){
builder.append(stack.pop());
}
return builder.toString();
}
}
思路3:
public class Solution {
public String reverseString(String s) {
if(s == null || s.equals("")){
return "";
}
char[] chararr = s.toCharArray();
for(int i=0; i<chararr.length/2; ++i){
char temp = chararr[i];
chararr[i] = chararr[chararr.length-i-1];
chararr[chararr.length-i-1] = temp;
}
return new String(chararr);
}
}
- #leetcode# 344 Reverse String
- Leetcode Reverse String 344
- LeetCode 344 Reverse String
- LeetCode 344 Reverse String
- LeetCode 344 Reverse String
- [leetcode 344]Reverse String
- LeetCode 344:Reverse String
- leetcode 344 Reverse String
- LeetCode-344 Reverse String
- leetcode 344 Reverse String
- leetcode 344 Reverse String
- LeetCode-344:Reverse String
- LeetCode 344 Reverse String
- LeetCode#344 Reverse String
- Leetcode-344-Reverse String
- Leetcode #344 Reverse String
- leetcode-344- Reverse String
- Leetcode 344 Reverse String
- 接口对象的实例化
- 年度创始人李志飞:出门问问打造接地气的人工智能
- Google账号登录不上Android Studio
- Android获取IPV4的方法
- maven 打包命名规则
- LeetCode-344:Reverse String
- How many integers can you find993 公约数和公倍数
- t2s串口操作
- 苹果企业号-通过网页下载应用,部署应用分发服务器
- MFC修改对话框及控件背景颜色 - 很轻松!
- Round Numbers((组合数 + 简单组合数学)||(数位dp))
- log4j同配置下多个进程写日志
- 逻辑地址 虚拟地址 基地址 物理地址
- 浅谈MVC、MVP和MVVM,以及iOS中的MVC