(一) 题目 : 字符串中的字符移动
题目: 字符串中的 字符移动
描述: 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变
思路1:
先将整个字符串翻转,再翻转每一个单词
运用栈的特性 进行入栈和出栈
思路2:
for循环倒置字符串,封成一个方法
还是先将整个字符串翻转,在将每一个单词翻转
(二) 代码及测试
package com.example.offer; import java.util.Stack; /** *题目: 字符串中的 字符移动 *描述: 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变 * *思路1: * 先将整个字符串翻转,再翻转每一个单词 * 运用栈的特性 进行入栈和出栈 * *思路2: * for循环倒置字符串,封成一个方法 * 还是先将整个字符串翻转,在将每一个单词翻转 * @author zhangchaocai * @create 2020-06-28 11:17 */ public class offer2 { public static void main(String[] args) { String s = "how are you"; String s1 = turnWord(s); //用栈 String s2 = reverseSentence(s); //字符拼接 StringBuffer System.out.println("反转前的字符为:" + s); System.out.println("用字符拼接,反转后的字符为:" + s2); System.out.println("用栈,反转后的字符为:" + s1); } /************************ 字符拼接 ********************************/ private static String reverseSentence(String s) { if(s == null || s.length() == 0 || s.trim().length() == 0){ return s; } String blank = " "; String senReverse = reverse(s); String[] split = senReverse.split(blank); StringBuffer sb = new StringBuffer(); for (int i = 0; i < split.length - 1; i++) { sb.append(reverse(split[i])).append(blank); } sb.append(reverse(split[split.length - 1]));; return String.valueOf(sb); } private static String reverse(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length() - 1; i >= 0 ; i--) { sb.append(s.charAt(i)); } return String.valueOf(sb); } /************************ 栈 ********************************/ private static String turnWord(String s) { if(s == null || s.length() == 0 || s.trim().length() == 0){ return s; } String stackChar = StackMethod(s); String[] s1 = stackChar.split(" "); String blank = " "; StringBuffer sb = new StringBuffer(); for (int i = 0; i < s1.length - 1; i++) { sb.append(StackMethod(s1[i])).append(blank); } sb.append(StackMethod(s1[s1.length - 1]));; return String.valueOf(sb); } public static String StackMethod(String s){ Stack<Character> stack = new Stack<>(); String returnChar = ""; for (int i = 0; i < s.length() ; i++) { stack.push(s.charAt(i)); } for (int i = 0; i < s.length() ; i++) { Character pop = stack.pop(); returnChar += pop; } return returnChar; } }
(三) 运行结果
又下起了小雨