最长的指定瑕疵度的元音子串
输入描述
开头和结尾都是元音字母(aeiouAEIOU)的字符串为元音字符串,其中混杂的非元音字母数量为其瑕疵度。比如:
“a” 、 “aa”是元音字符串,其瑕疵度都为0
“aiur”不是元音字符串(结尾不是元音字符)
“abira”是元音字符串,其瑕疵度为2
给定一个字符串,请找出指定瑕疵度的最长元音字符子串,并输出其长度,如果找不到满足条件的元音字符子串,输出0。
子串:字符串中任意个连续的字符组成的子序列称为该字符串的子串。
输出描述
首行输入是一个整数,表示预期的瑕疵度flaw,取值范围[0, 65535]。
接下来一行是一个仅由字符a-z和A-Z组成的字符串,字符串长度(0, 65535]。
输入 | 输出 | 说明 |
---|---|---|
0 asdbuiodevauufgh | 3 | uio为瑕疵度为0的最长子串,故长度为3 当然auu也是 |
2 aeueo | 3 | 0 |
解析
该题考查正则表达式的使用。 其中一个隐含的点就是正则匹配时不能找出所有满足的子串。因此可以匹配到一个就把开始字符替换掉。这样能尽量多的找出满足条件的子串。
源码
java">import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class T22 {
public static void main(String[] args) {
int flaw =1; // 瑕疵度
String inputStr = "asdabbuiooodevauufghu"; // 匹配字符
//开头是元音 结尾是元音 中间出现的非元音字符是瑕疵度
String regex="";
if(flaw==0){
regex="[aeiouAEIOU]{1,}";
}else{
regex="[aeiouAEIOU]{1}";
for(int i=0;i<flaw;i++){
regex+="[^aeiouAEIOU]{1}[aeiouAEIOU]*";
}
regex+="[aeiouAEIOU]{1}";
}
System.out.println(regex);
System.out.println(inputStr.matches("[aeiou]{1}"));
// while(inputStr.contains("[aeiou]{1}"))
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(inputStr);
int max=0;
while(matcher.find()){
System.out.println(inputStr.substring(matcher.start(), matcher.end()));
if(matcher.end()-matcher.start()>max){
max=matcher.end()-matcher.start();
}
StringBuilder sb=new StringBuilder(inputStr);
sb.setCharAt(matcher.start(), '_');//每次匹配到之后就把开始字符替换掉 可以一直往后匹配。
inputStr=sb.toString();
matcher=pattern.matcher(inputStr);
}
System.out.println("长度:"+max);
}
}