思路:
- String[] data = s.split(" ",-1); 能够让几个空格对应几个空数据,后面反转后能添加空格补齐
2.或者先将所有数据大小写字母转换。然后从n-1开始到0,如果i位置遇到空格,使得[i+1,j]是一个非空串,然后放入StringBuilder中,这里主要是边界条件比较麻烦。i-- 不能小于0
import java.util.*;
public class Solution {
public String trans(String s, int n) {
// write code here
if(s == null || s.length() <= 1 || n<=1){
return s;
}
String[] data = s.split(" ",-1);
StringBuilder sb = new StringBuilder();
for(int i = data.length - 1; i >= 0 ;i --){
sb.append(transSignle(data[i]));
if(i != 0){
sb.append(" ");
}
}
return sb.toString();
}
private String transSignle(String s){
StringBuilder sb = new StringBuilder();
char[] data = s.toCharArray();
for(int i = 0;i < data.length; i++){
if(data[i] >= 'a' && data[i] <= 'z'){
sb.append((char)(data[i] -'a' + 'A'));
}else if(data[i] >= 'A' && data[i] <= 'Z'){
sb.append((char)(data[i] - 'A' + 'a'));
}else{
sb.append(data[i]);
}
}
return sb.toString();
}
}