1、一串字母判断是否为合法字符串,规则有三
(1).字母可以全部是大写
(2).字母可以全部是小写
(3).可以首字母是大写,其余字母全小写 除此之外全不合法,返回值为布尔型,合法返回True,不合法返回False
public boolean isLegalWord(String world) {
Pattern pattern1 = Pattern.compile("[a-z]*");
Pattern pattern2 = Pattern.compile("[A-Z]*");
Pattern pattern3 = Pattern.compile("[A-Z][a-z]*");
Matcher matcher1 = pattern1.matcher(world);
Matcher matcher2 = pattern2.matcher(world);
Matcher matcher3 = pattern3.matcher(world);
if (matcher1.matches()) {
isAllLowerCase = true;
} else if (matcher2.matches()) {
isAllUpperCase = true;
} else if (matcher3.matches()) {
isStartUpperCase = true;
} else {
}
if (isAllLowerCase || isAllUpperCase || isStartUpperCase) {
return true;
} else {
return false;
}
}
2、请找出数组中出现次数最多的元素
public class FindMaxCounter {
public static void main(String[] args) {
int array[] = { 1, 2, 3, 2, 3, 3 };
int number = findNumber(array);
System.out.println("出现次数最多的数字是:" + number);
}
public static int findNumber(int[] array) {
// 建立一个新数组保存元素出现的次数,其长度与原数组一致
int counterArray[] = new int[array.length];
// 将每个数字出现的次数存入counterArray
for (int i = 0; i < array.length; i++) {
int counter = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] == array[i]) {
counter++;
}
}
counterArray[i] = counter;
}
// 从counterArray找出最大值,即现次数最多的元素
int maxCounter = counterArray[0];
int maxCounterIndex = 0;
for (int i = 0; i < counterArray.length - 1; i++) {
if (counterArray[i + 1] > maxCounter) {
maxCounter = counterArray[i + 1];
maxCounterIndex = i + 1;
}
}
// 找出出现次数最多的元素
int number = array[maxCounterIndex];
return number;
}
}