题目:反转字符串 写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串
思路:1.利用栈先进后出的特性;
import java.util.*; public class Solution { public String solve (String str) { String s=""; Stack<Character> st = new Stack<>(); for (int i = 0; i < str.length(); i++) { st.push(str.charAt(i)); } for (int i = 0; i < str.length(); i++) { s+=st.pop(); } return s; } }
import java.util.*; public class Solution { /** * 反转字符串 * @param str string字符串 * @return string字符串 */ public String solve (String str) { StringBuffer stringBuffer=new StringBuffer(str); return stringBuffer.reverse().toString(); } }
import java.util.*; public class Solution { /** * 反转字符串 * @param str string字符串 * @return string字符串 */ public String solve (String str) { String s=""; char[] chars=str.toCharArray(); for (int i = (str.length()-1); i>=0; i--) { s +=chars[i]; } return s; } }