Java brush questions (3)

 On the third day of the Codewars brushing, the string question:

Issue three topics:

 

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

Answer: (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;

}

This is a relatively common solution, for the reference of the Java 8 method of traversing strings:

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

// CharSequence interface adds a new method called chars(), the signature of the method looks like this

public default IntStream chars()

IntStream provides a mapToObj method to perform the conversion of Int type to any other type. The signature of this method and its related function interface IntFunction are as follows:

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

According to the signature of mapToObj, the conversion and output of integer type to character type can be implemented like this:

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

so

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

All characters can be traversed and stored in ASCII order.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324635341&siteId=291194637