方法一 使用栈
一定要注意前后空格问题
import java.util.*; public class Solution { public String trans (String s, int n) { // write code here Deque<String> stack=new ArrayDeque<>(); String[] strs=s.split(" ",-1);//若干最后n位都是切割符,split(" ")不会继续切分,split(" ", -1)会继续切分 for(String str:strs){ stack.push(str); } StringBuilder res=new StringBuilder(); while(!stack.isEmpty()){ StringBuilder temp=new StringBuilder(stack.pop()); int len=temp.length(); for(int i=0;i<len;i++){ if(temp.charAt(i)>='A'&&temp.charAt(i)<='Z'){ temp.setCharAt(i,(char)(temp.charAt(i)-'A'+'a')); }else if(temp.charAt(i)>='a'&&temp.charAt(i)<='z'){ temp.setCharAt(i,(char)(temp.charAt(i)-'a'+'A')); } } res.append(temp); res.append(" "); } res.deleteCharAt(res.length()-1); return res.toString(); } }
方法二,二次翻转
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param n int整型 * @return string字符串 */ public String trans (String s, int n) { if(n==0){ return s; } StringBuilder res=new StringBuilder(); for(int i=0;i<n;i++){ char ch=s.charAt(i); if(ch>='A'&&ch<='Z'){ res.append(Character.toLowerCase(ch)); }else if(ch>='a'&&ch<='z'){ res.append(Character.toUpperCase(ch)); }else{ res.append(ch); } } res.reverse(); for(int i=0;i<n;i++){ int j=i; while(j<n&&res.charAt(j)!=' '){ j++; } String temp=res.substring(i,j); StringBuilder builder=new StringBuilder(temp); builder.reverse(); res.replace(i,j,builder.toString()); i=j; } return res.toString(); } }