蓝桥杯音节判断
07、音节判断(思维比较重要)
【问题描述】
小明对类似于 hello 这种单词非常感兴趣,这种单词可以正好分为四段,第一段由一个或多个辅音字母组成,第二段由一个或多个元音字母组成,第三段由一个或多个辅音字母组成,第
给定一个单词,请判断这个单词是否也是这种单词,如果是请输出yes,否则请输出no。
元音字母包括 a, e, i, o, u,共五个,其他均为辅音字母。
【输入格式】
输入一行,包含一个单词,单词中只包含小写英文字母。
【输出格式】
输出答案,或者为yes,或者为no。
【样例输入】
lanqiao
【样例输出】
yes
【样例输入】
world
【样例输出】
no
【评测用例规模与约定】
对于所有评测用例,单词中的字母个数不超过100
题目解读:
这种题目比较好读懂,接着实现就行了,一定要考虑每种情况,对比自己的和老师讲的
- 1、自己
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String str = scanner.next();
scanner.nextLine();
String string = "aeiou";
// scanner.nextLine();
char first = str.charAt(0);
if (string.contains(first+"")){
System.out.println("no");
return;
}
char[] arr = str.toCharArray();
boolean flag = true;
int two = 0;
for (int i = 1; i < arr.length; i++) {
boolean t = string.contains(arr[i]+"");
if ((t) && flag) {
two++;
flag = false;
}
if (!t) {
flag = true;
}
if (two > 2) {
System.out.println("no");
return;
}
}
if (two == 2) {
System.out.println("yes");
}else {
System.out.println("no");
}
}
}
总结:代码整体比较low,但是中间有个flag还算有点想法!
- 2、正则表达式解法
static Pattern p = Pattern.compile("[^aeiou]+[aeiou]+[^aeiou]+[aeiou]+");
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (true) { //死循环是为了测试
if (work1())
System.out.println("yes");
else
System.out.println("no");
}
}
static boolean work1() {
String word = sc.nextLine();
Matcher m = p.matcher(word);
return m.matches();
}
总结:正则表达式定义格式:
^和正则表达式一样,代表开始,不包含,不加表示包含
matcher:匹配器
Patten p = Patten.compile("[^**]+[**]+[^**]+...+[^**]+");
p.matcher(string);
- 3、常规解法
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (true) { //死循环是为了测试
if (work1())
System.out.println("yes");
else
System.out.println("no");
}
}
static boolean isYuan(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
static boolean work2() {
String word = sc.nextLine();
int size = word.length();
if (size < 4)
return false;
if (isYuan(word.charAt(0)) || !isYuan(word.charAt(size - 1)))
return false;
int[] h = new int[size];
for (int i = 0; i < size; ++i) {
if (isYuan(word.charAt(i)))
h[i] = 1;
else
h[i] = 0;
} //传说中的 0 、1表示法,转换思维,用整数来比较,很牛逼
int cnt = 0;
for (int i = 1; i < size; ++i) {
if (h[i - 1] + h[i] == 1) cnt++;
}
return cnt == 3;
}
总结:换了一种思维方式,可以把元音和辅音分成两类,1表示元音,0表示辅音,用一个新数组表示,因为什么?
就两种情况,不是 0 就是 1,所以这样就会好操作许多!

浙公网安备 33010602011771号