给定一个字符串,请找出指定瑕疵度的最长元音字符子串,并输出其长度,如果找不到满足条件的元音字符子串,输出0

题目描述
开头和结尾都是元音字母(aeiouAEIOU)的字符串为元音字符串,其中混杂的非元音字母数量为其瑕疵度。比如:

“a” 、 “aa”是元音字符串,其瑕疵度都为0
“aiur”不是元音字符串(结尾不是元音字符)
“abira”是元音字符串,其瑕疵度为2
给定一个字符串,请找出指定瑕疵度的最长元音字符子串,并输出其长度,如果找不到满足条件的元音字符子串,输出0。

子串:字符串中任意个连续的字符组成的子序列称为该字符串的子串。

输入描述
首行输入是一个整数,表示预期的瑕疵度flaw,取值范围[0, 65535]。

接下来一行是一个仅由字符a-z和A-Z组成的字符串,字符串长度(0, 65535]。

输出描述
输出为一个整数,代表满足条件的元音字符子串的长度。

用例
输入 0
asdbuiodevauufgh
输出 3

代码解析:

static String soundChar = "aeiouAEIOU";
public static void soundString() {
Scanner scanner = new Scanner(System.in);
int preCount = scanner.nextInt();
String soundStr = scanner.nextLine();
if ("".equals(soundStr)) {
soundStr = scanner.nextLine();
}
// 求出 所有 元音字符 子串 和 瑕疵度 , 根据瑕疵度 获取字串,最后返回长度
Map<Integer, List> map = new HashMap<>();
for (int i = 0; i < soundStr.length(); i++) {
findSoundStr(soundStr, i, soundStr.length() - 1, map);
}
List list = map.get(preCount);
int maxLen = 0;
if (list != null) {
for (int i = 0; i < list.size(); i++) {
maxLen = Math.max(maxLen, list.get(i).length());
}
}
System.out.println(maxLen);
}

// 从后往前找
private static void tailToStart(String source, int start, int end, Map<Integer, List> map) {
if (start == end) {
return;
}
String tempSource = source.substring(start, end);
// 元音字符
if (soundChar.contains(tempSource.charAt(0) + "") && soundChar.contains(tempSource.charAt(tempSource.length() - 1) + "")) {
// 瑕疵度
int count = countSound(tempSource);
List list = map.get(count);
if (list == null) {
list = new ArrayList();
}
list.add(tempSource);
map.put(count, list);
}
tailToStart(source, start, end - 1, map);
}

// 从前往后找
private static void findSoundStr(String source, int start, int end, Map<Integer, List> map) {
if (start == end) {
return;
}
String tempSource = source.substring(start, end);
// 元音字符
if (soundChar.contains(tempSource.charAt(0) + "") && soundChar.contains(tempSource.charAt(tempSource.length() - 1) + "")) {
// 瑕疵度
int count = countSound(tempSource);
List list = map.get(count);
if (list == null) {
list = new ArrayList();
}
list.add(tempSource);
map.put(count, list);
}
tailToStart(source, start, end - 1, map);
}

private static int countSound(String soudStr) {
// 替换所有元音字符
String s = soudStr.replaceAll(String.join("|", soundChar.split("")), "");
// 非元音字符 个数 即为 长度
return s.length();
}

posted @   vello  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示