我是Java初学者,我想知道是否有办法将一个char数组中的字符与另一个char阵列中的其他字符进行比较,以查看它们是否有匹配的字符。不要看它们是否像大多数例子所解释的那样,在同一序列中包含完全相同的字符。
例如:
char [] word1= {'a','c','f','b','e'};
char[] word2= {'a','b','c','d','e','h','j','f','i','m'};
并使用maybe if语句表示单词1包含单词2中的字符,因此它是正确的。否则,如果单词2缺少单词1所包含的至少一个字符,则这是不正确的。
试试这个。它将报告其中一个数组是否包含另一个数组的所有字符。我使用了字符串并将它们转换为数组以便于编码。
String[][] testData =
{ {"axyzx","xxyzaa"},
{"aaxyz","aaax"},
{"axa","a"},
{"arrs","asrrrs"},
{"acfbe","abcdehjfim"}};
for (String[] words : testData) {
boolean result = contains(words[0].toCharArray(), words[1].toCharArray());
String output = String.format("%s contains all %s","'"+words[0]+"'","'"+words[1]+"'");
System.out.printf("%34s - %b%n", output, result);
output = String.format("%s contains all %s","'"+words[1]+"'","'"+words[0]+"'");
result = contains(words[1].toCharArray(), words[0].toCharArray());
System.out.printf("%34s - %b%n%n", output, result);
}
打印
'axyzx' contains all 'xxyzaa' - false
'xxyzaa' contains all 'axyzx' - true
'aaxyz' contains all 'aaax' - false
'aaax' contains all 'aaxyz' - false
'axa' contains all 'a' - true
'a' contains all 'axa' - false
'arrs' contains all 'asrrrs' - false
'asrrrs' contains all 'arrs' - true
'acfbe' contains all 'abcdehjfim' - false
'abcdehjfim' contains all 'acfbe' - true
- 使用映射对第二个数组中的字符进行频率计数
- 现在使用第一个数组遍历映射,在找到字符时递减字符计数。当计数达到0时,将
null
分配给该值 - 如果CCD_ 4现在是"0";"空";,第一个数组包含第二个数组的所有字符
// see if first array contains all of second array,
// regardless of order of the characters
public static boolean contains(char[] ch1, char[] ch2) {
// a smaller array cannot possible contain the same
// characters as a larger array
if (ch1.length < ch2.length) {
return false;
}
Map<Character,Integer> map = new HashMap<>();
// Do a frequency count
for(char c : ch2) {
map.compute(c, (k,v)->v == null ? 1 : v+1);
}
// now decrement count for each occurrence
// of character in first array, setting value to
// null when count reaches 0.
for(char c : ch1) {
map.computeIfPresent(c, (k,v)-> v <= 1 ? null : v-1);
}
return map.isEmpty();
}
我创建了一个小片段,认为这就是您想要的:
public class Main {
public static void main(String[] args) {
char[] word1= {'a','c','f','b','e'};
char[] word2= {'a','b','c','d','e','h','j','f','i','m'};
System.out.println(Contains(word1, word2));
}
private static boolean Contains(char[] arr1, char[] arr2) {
for (int i = 0; i < arr1.length; i++) {
boolean containsChar = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) containsChar = true;
}
if (!containsChar) return false; // arr2 does not contain arr1[i]
}
return true;
}
}