Java 刷题(三)

 Codewars 刷题第三天,字符串问题:

第三期题目:

Write a function that will return the count of distinct case-insensitive alphabetic

characters and numeric digits that occur more than once in the input string.

The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

"abcde" -> 0 # no characters repeats more than once

"aabbcde" -> 2 # 'a' and 'b'

"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)

"indivisibility" -> 1 # 'i' occurs six times

"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice

"aA11" -> 2 # 'a' and '1'

"ABBA" -> 2 # 'A' and 'B' each occur twice

答案:(已AC)

public static int duplicateCount(String text) {

// Write your code here

int num=0;

int [] times_all=new int [36];

for(int i=0;i<text.length();i++){

if(text.charAt(i)<58&&text.charAt(i)>46){

times_all[text.charAt(i)-47]+=1;

}else if(text.charAt(i)<123&&text.charAt(i)>96){

times_all[text.charAt(i)-87]+=1;

}else if(text.charAt(i)<91&&text.charAt(i)>64){

times_all[text.charAt(i)-55]+=1;

}

}

for(int j=0;j<times_all.length;j++){

if(times_all[j]>1)

num++;

}

return num;

}

这是一个相对普通点的解决方案,对于遍历字符串Java 8的方法给大家参考:

str.chars().forEach(ch -> System.out.println((char)ch));

//CharSequence接口新添加了一个方法叫做chars(),方法的签名是这个样子的

public default IntStream chars()

IntStream提供了一个mapToObj方法用来执行Int类型到其它任意类型的转换,该方法的签名和其相关的函数接口IntFunction如下:

<U> Stream<U> mapToObj(IntFunction<? extends U> mapper);@FunctionalInterfacepublic interface IntFunction<R> {R apply(int value);}

根据mapToObj的签名,整型类型到字符类型的转换和输出就可以这样实现了:

str.chars().mapToObj(ch -> Character.valueOf((char)ch)).forEach(System.out::println);

所以

text.toUpperCase().chars().forEach(ch->times_all[ch<58?ch-47:ch-55]+=1);

就可以遍历出所有字符并按ASII 顺序存储。

猜你喜欢

转载自www.cnblogs.com/Jaiken/p/8904255.html