codeforces 水题的优化,记录一下。
字符串满足规则时,进行大小写转换。
一般会直接将两种情况分别进行判断,那就相当于遍历了数组两次。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 题意:给一个字符串,对于以下两种情况进行大小写互转。其余情况不变
* ①、全部为大写 ==> 全部小写
* ②、首字母小写,其余大写。 ==> 首字母大写,其余小写
*/
public class Main {
/**
* 判断除字符串是否符合第一种规则
*/
public static boolean isAllUpper(String str) {
// 只要除了首字母以外的字母出现小写,即不符合规则。应该转换
char temp;
for (int index = 0; index < str.length(); index++) {
temp = str.charAt(index);
if (temp <= 'z' && temp >= 'a') {
return false;
}
}
return true;
}
/**
* 判断除字符串是否符合第二种规则
*/
public static boolean isLowUpper(String str) {
// 只要除了首字母以外的字母出现小写,即不符合规则。应该转换
if (str.charAt(0) <= 'Z' && str.charAt(0) >= 'A') {
return false;
}
char temp;
for (int index = 1; index < str.length(); index++) {
temp = str.charAt(index);
if (temp <= 'z' && temp >= 'a') {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
String inputWord; // 输入的单词
String changeWord;// 转换之后的单词
while (in.hasNext()) {
inputWord = in.next();
changeWord = inputWord;
if (isAllUpper(inputWord)) {
changeWord = inputWord.toLowerCase();
}else if(isLowUpper(inputWord)){
changeWord = inputWord.substring(0, 1).toUpperCase() + inputWord.substring(1).toLowerCase();
}
out.println(changeWord);
}
out.flush();
}
}
优化方案:
思考一下,就会发现一个稍加优化的方案:
区分两种情况,仅仅在于首字母的不同。
所以我们可以这样,先合并判断除首字母外其他的字母,再分别判断首字母。
这样就减少了遍历数组的次数,次数减半。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 题意:给一个字符串,对于以下两种情况进行大小写互转。其余情况不变
* ①、全部为大写 ==> 全部小写
* ②、首字母小写,其余大写。 ==> 首字母大写,其余小写
*/
public class Main {
/**
* 判断除首字母外,是否都是大写。
*/
public static boolean isUpper(String str) {
// 只要除了首字母以外的字母出现小写,即不符合规则。应该转换
for (int index = 1; index < str.length(); index++) {
char temp = str.charAt(index);
if (temp <= 'z' && temp >= 'a') {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
String inputWord; // 输入的单词
String changeWord;// 转换之后的单词
while (in.hasNext()) {
inputWord = in.next();
changeWord = inputWord;
char temp = inputWord.charAt(0);
if (isUpper(inputWord)) {
//两种情况除了首字母外,都一样。为了减少循环遍历数组的次数,可以把首字母单独取出来进行判断。
if(temp <= 'z' && temp >= 'a'){
changeWord = inputWord.substring(0, 1).toUpperCase() + inputWord.substring(1).toLowerCase();
}else{
changeWord = inputWord.toLowerCase();
}
}
out.println(changeWord);
}
out.flush();
}
}