题目描述:
对于一个给定的字符串,我们需要在线性(也就是O(n))的时间里对它做一些变形。首先这个字符串中包含着一些空格,就像”Hello World”一样,然后我们要做的是把着个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。比如”Hello World”变形后就变成了”wORLD hELLO”。
/**
*
* @author 过路的守望
*
*/
public class Transform {
public static void main(String[] args) {
System.out.println(new Transform().trans(" Now Co der ", 16));
}
public String trans(String s, int n) {
if (n < 1 || n > 500 || s == null || s.equals("")) {
return "";
}
if ("".equals(s.trim())) {
return s;
}
int len = s.length();
char[] str = s.toCharArray();
/*
* temp为单词,empty为单词间的空格数(1个或多个),result为之前已处理好的字符串
*/
String temp = "";
String empty = "";
String result = "";
for (int i = 0; i < len; i++) {
if ('a' <= str[i] && str[i] <= 'z') {
str[i] = (char) (str[i] - 32);
temp = temp + str[i];
continue;
} else if ('A' <= str[i] && str[i] <= 'Z') {
str[i] = (char) (str[i] + 32);
temp = temp + str[i];
continue;
} else {
empty = empty + " ";
/*
* 字符串的最后一个字符是空格的情形
*/
if (i == len - 1) {
return result = empty + temp + result;
}
/*
* 空格的下一个字符不是空格的情形
*/
if (str[i + 1] != ' ') {
result = empty + temp + result;
temp = "";
empty = "";
}
}
}
return empty + temp + result;
}
}