一、题目描述
小明对类似于 hello 这种单词非常感兴趣,这种单词可以正好分为四段,第一段由一个或多个辅音字母组成,第二段由一个或多个元音字母组成,第三段由一个或多个辅音字母组成,第四段由一个或多个元音字母组成。
给定一个单词,请判断这个单词是否也是这种单词,如果是请输出 yes,否则请输出 no。
元音字母包括 a, e, i, o, u,共五个,其他均为辅音字母。
输入格式
- 输入一行,包含一个单词,单词中只包含小写英文字母。
输出格式
- 输出答案,或者为 yes,或者为 no。
样例输入
lanqiao
样例输出
yes
样例输入
world
样例输出
no
评测用例规模与约定
- 对于所有评测用例,单词中的字母个数不超过100。
方法一:分段统计
- 先特判一下。
- 分段处理,最后一定要加上
i == s.length && ...
,因为可能会存在这种样例qeqeq
。
* 算法的缺点:如果要判断 n
段,需要写 n
个 while(...)
,不通用。
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static int[] vowel, cons;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
PrintWriter pw = new PrintWriter(System.out, true); //自动刷新
char[] s = sc.next().toCharArray();
vowel = new int[26]; //存储元音
cons = new int[26]; //存储辅音
for (char c = 'a'; c <= 'z'; c++) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowel[c-'a']++;
else
cons[c-'a']++;
}
if (check(s)) System.out.println("yes");
else System.out.println("no");
}
private static boolean check(char[] s) {
if (s.length < 4)
return false;
//第一个字符非辅音或者最后一个字母非元音
if (cons[s[0]-'a'] == 0 || vowel[s[s.length-1]-'a'] == 0)
return false;
int i = 0;
boolean a = false, b = false, c = false, d = false;
while (i < s.length && cons[s[i]-'a'] > 0) {
a = true;
i++;
}
while (i < s.length && vowel[s[i]-'a'] > 0) {
b = true;
i++;
}
while (i < s.length && cons[s[i]-'a'] > 0) {
c = true;
i++;
}
while (i < s.length && vowel[s[i]-'a'] > 0) {
d = true;
i++;
}
if (i == s.length && a && b && c && d)
return true;
return false;
}
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:统计高度和的为 1 的个数
- 元音 vowel 的高度设为 1,辅音 cons 的高度设为 0.
- 最后统计两个字符之间的高度和为 1 的数量是否为 3 即可。
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static int[] vowel, cons;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
PrintWriter pw = new PrintWriter(System.out, true); //自动刷新
char[] s = sc.next().toCharArray();
if (check(s))
System.out.println("yes");
else System.out.println("NO");
}
private static boolean check(char[] s) {
if (s.length < 4)
return false;
if (isVowel(s[0]) || !isVowel(s[s.length-1]))
return false;
int[] arr = new int[s.length];
for (int i = 0; i < s.length; i++) {
if (isVowel(s[i]))
arr[i] = 1;
else
arr[i] = 0;
}
int cnt = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] + arr[i-1] == 1)
cnt++;
}
return cnt == 3;
}
private static boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,