假设您有一个像这样的字符串:
abaabbbbbaabba
计算指定字符在输入字符串中出现的次数,但前提是该字符仅连续出现一次。例如,如果字符是a
,
abaabbbbbaabba
^ x x ^
总数为2(aa
因为a
连续出现两次,所以不会计数)。
这与FizzBuzz有什么关系?
如果字符连续出现3次(或3的倍数),或连续出现5次(或5的倍数),则计数器递减。如果它是3 倍和 5倍的倍数,则计数器仍会递增。请记住,如果字符仅连续出现一次,则计数器也会增加;如果字符连续出现其他次数,则计数器将被忽略(上述情况除外)。
回顾一下,如果要匹配的字符串是a
,
input counter (explanation)
a 1 (single occurence)
aaa -1(multiple of 3)
aaaaa -1(multiple of 5)
aaaaaaaaaaaaaaa 1 (multiple of 15)
aa 0 (none of the above)
aba 2 (two single instances)
aaba 1 (one single occurence(+1) and one double occurence(ignored))
aaaba 0 (one single occurence(+1) and one triple (-1)
aaaaaa -1 (six is a multiple of three)
Java中的参考(未启用)实现:
import java.util.Scanner;
import java.util.regex.*;
public class StrMatcher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner to get user input
int total = 0;//Running total of matches
System.out.println("Enter a string: ");
String strBeingSearched = sc.nextLine(); //String that will be searched
System.out.println("Enter string to match with: ");
String strBeingMatched = sc.nextLine(); //Substring used for searching
//Simple regex matcher
Pattern pattern = Pattern.compile("(" + strBeingMatched + ")+");
Matcher matcher = pattern.matcher(strBeingSearched);
while(matcher.find()){ //While there are still matches
int length = matcher.end() - matcher.start();
int numberOfTimes = length/strBeingMatched.length();//Calculate how many times in a row the string is matched
if((numberOfTimes == 1)||((numberOfTimes % 3 == 0) && (numberOfTimes % 5 == 0))){
total++; //Increment counter if single match or divisible by 15
} else if((numberOfTimes % 3 == 0)||(numberOfTimes % 5 == 0)) {
total--; //Decrement counter if divisible by 3 or 5 (but not 15)
}
strBeingSearched = strBeingSearched.substring(matcher.end());
matcher = pattern.matcher(strBeingSearched); //Replace string/matcher and repeat
}
System.out.println(total);
}
}
- 将搜索的字符串可以是任意长度,但是模式只能是单个字符。
- 这两个字符串都不会包含正则表达式特殊字符。
- 这是代码高尔夫球;以字节为单位的最短程序获胜。
- 没有标准漏洞。