我在HackerRank上尝试了一个问题:
基本上是想让我寻找在每个字符串数组元素中重复的字符元素。
描述
有一组岩石,每个岩石都有不同的矿物嵌入其中。每种矿物都是在ascii(a - z)范围内用小写字母指定的。
岩石中可能有多处矿点。一种矿物被称为宝石,如果它发生至少一次在每个岩石在集合中。
给出嵌在每块岩石中的矿物清单,显示收藏中宝石种类的数量。
示例
arr = ['abc','abc','bc']矿物b和c出现在每块岩石中,因此有2宝石。
我的密码
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'gemstones' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING_ARRAY arr as parameter.
*/
public static int gemstones(List<String> arr) {
// Write your code here
String str[] = new String[arr.size()];
// ArrayList to Array Conversion
for (int j = 0; j < arr.size(); j++) {
str[j] = arr.get(j);
}
int c=0;
int count[]=new int[26];
for(int i=0;i<str.length;i++){
String x=str[i];
for(int j=0;j<26;j++){
char y=(char)(j+97);
if(x.indexOf(y)!=-1)
count[j]++;
}
}
for(int i=0;i<26;i++){
if(count[i]==str.length)
c++;
}
return c;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<String> arr = IntStream.range(0, n).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
int result = Result.gemstones(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}这是我只能设计public static int gemstones(List<String> arr)的代码。
我的方法很简单
我为这26个字母创建了一个整数数组,并检查了所有数组元素中是否存在任何字母。如果是的话,我就把计数器增加1。
我的问题
在使用自定义输入选项时,答案应该是:0。
然而,我无法通过这个。
发布于 2021-09-05 09:20:24
要验证您的算法,我们所能做的就是:
我们所知道的
剖析代码
下面,我补充了一些评论,以表达我所理解的意愿:
String str[] = new String[arr.size()]; // array of rocks
// ArrayList to Array Conversion
for (int j = 0; j < arr.size(); j++) {
str[j] = arr.get(j);
}
int c=0; // counter for gemstones
int count[]=new int[26]; // 26 counts (for each of the 26 letters in alphabet)
for(int i=0;i<str.length;i++){ // for each rock, count letters
String x=str[i]; // rock to test
for(int j=0;j<26;j++){ // for each letter in alphabet
char y=(char)(j+97); // from decimal ASCII code to lower-case char
if(x.indexOf(y)!=-1) // if current letter-char found in rock
count[j]++; // increment letter-count
}
} // test next rock against alphabet (and count)
for(int i=0;i<26;i++){ // test each letter counter if it satisfies (at least once per rock)
if(count[i]==str.length)
c++; // if satisfied (gemstone found) then increment counter
}
return c; // count of gemstones foundhttps://stackoverflow.com/questions/69060855
复制相似问题