題目
題目描述:
定義當一個字符串只有元音字母一(a,e,i,o,u,A,E,l,O,U)組成,
稱為元音字符串,現給定一個字符串,請找出其中最長的元音字符串,并返回其長度,如果找不到請返回0,
字符串中任意一個連續字符組成的子序列稱為該字符串的子串
輸入描述:
一個字符串其長度0<length ,字符串僅由字符a-z或A-Z組成
輸出描述:
一個整數,表示最長的元音字符子串的長度
示例1:
輸入
asdbuiodevauufgh
輸出
3
說明:
最長的元音字符子串為uio和auu長度都為3,因此輸出3
思路
正則表達式
利用正則表達式,找到所有匹配的子串,利用matcher.end-matcher.start可以計算當前匹配的長度。最后統計最長長度即可
遍歷統計
傳統的遍歷,找到第一個匹配的字符,然后計算當前有多少個連續匹配的字符,最后得到最大長度即可
題解
正則表達式
package hwod;import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class TheLongestVowelSubStr {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s = sc.nextLine();System.out.println(theLongestVowelSubStr(s));}private static int theLongestVowelSubStr(String s) {int res = 0;Pattern p = Pattern.compile("[aeiouAEIOU]+");Matcher matcher = p.matcher(s);while (matcher.find()) {res = Math.max(res, matcher.end() - matcher.start());}return res;}
}
遍歷統計
package hwod;import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class TheLongestVowelSubStr {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s = sc.nextLine();System.out.println(theLongestVowelSubStr(s));}private static int theLongestVowelSubStr(String s) {s = s.toLowerCase();List<Character> list = Arrays.asList('a', 'e', 'i', 'o', 'u');int res = 0;for (int i = 0; i < s.length(); i++) {if (list.contains(s.charAt(i))) {int j = i + 1;while (j < s.length() && list.contains(s.charAt(j))) {j++;}res = Math.max(res, j - i);i = j - 1;}}return res;}
}
推薦
如果你對本系列的其他題目感興趣,可以參考華為OD機試真題及題解(JAVA),查看當前專欄更新的所有題目。