YOG*_*IYO 5 java algorithm function
给定一个字符串,找到具有相同元音和辅音数量的最长子字符串.
澄清:我不确定,我们是否可以生成一个新字符串,或者子字符串必须是原始字符串的一部分?到目前为止我有这个,
代码片段:
Scanner scanner = new Scanner(System.in);
String string = new String(scanner.next());
int lengthOfString = string.length();
int vowelCount = 0;
int consCount = 0;
for (int i = 0; i < lengthOfString; i++) {
if (string.charAt(i) == 'u' || string.charAt(i) == 'e' || string.charAt(i) == 'i'
|| string.charAt(i) == 'o' || string.charAt(i) == 'a' ) {
vowelCount++;
} else {
consCount++;
}
}
System.out.println(vowelCount);
Run Code Online (Sandbox Code Playgroud)
编辑我得到了计数工作,但我如何创建子字符串?
要找到辅音和元音数量相等的最长子串,请开始查找最大长度的子串,并逐渐减少所需的长度,直到找到符合条件的子串。
这将允许您短路操作。
public static String findLongestSubstring(String str) {
for (int len = str.length(); len >= 2; len--) {
for (int i = 0; i <= str.length() - len; i++) {
String substr = str.substring(i, i + len);
int vowels = countVowels(substr);
int consonants = len - vowels;
if (vowels == consonants) {
return substr;
}
}
}
return "";
}
private static int countVowels(String str) {
return str.replaceAll("[^AEIOUaeiou]+", "").length();
}
Run Code Online (Sandbox Code Playgroud)