两个字符串中有多少个字符相同
经过多次搜索没有结果,我来请求你的帮助。我有一个小问题。我有两个字符串:两个字符串中有多少个字符相同
String values = "acceikoquy";
String values2 = "achips";
我会得到相同的字符数所以在这里:
3
你有任何想法如何做到这一点?
我的代码:
String values = "acceikoquy";
String values2 = "achips";
int test = StringUtils.countMatches(values, values2);
System.out.println(test);
事情是这样的:
public static int sameCharsCount(String left, String right, boolean countDuplicates) {
if ((null == left) || (null == right))
return 0;
HashMap<Character, Integer> occurence = new HashMap<Character, Integer>();
for (int i = 0; i < left.length(); ++i) {
Character ch = left.charAt(i);
if (!occurence.containsKey(ch))
occurence.put(ch, 1);
else
occurence.put(ch, occurence.get(ch) + 1);
}
int result = 0;
for (int i = 0; i < right.length(); ++i) {
Character ch = right.charAt(i);
if (occurence.containsKey(ch)) {
result += 1;
if (!countDuplicates || occurence.get(ch) <= 1)
occurence.remove(ch);
else
occurence.put(ch, occurence.get(ch) - 1);
}
}
return result;
}
...
String values = "acceikoquy";
String values2 = "achips";
//TODO: put true or false if you want to count duplicates or not
int result = sameCharsCount(values, values2, true); // <- returns 3
int withDups = sameCharsCount("aaba", "caa", true); // <- 2 (two 'a' are shared)
int noDups = sameCharsCount("aaba", "caa", false); // <- 1 (just a fact, 'a' is shared)
谢谢兄弟你救了我的命 – Julien 2014-10-02 10:34:54
您可以用这种方式
String values = "acxa";
String values2 = "abada";
int count=0;
List<Character> list=new ArrayList<>();
List<Character> list1=new ArrayList<>();
for(int i=0;i<values2.length();i++){
list.add(values2.charAt(i));
}
for(int i=0;i<values.length();i++){
list1.add(values.charAt(i));
}
ListIterator<Character> listIterator=list.listIterator();
while (listIterator.hasNext()){
char val=listIterator.next();
if(list1.toString().contains(""+val)){
count++;
listIterator.remove();
int index=list1.indexOf(val);
list1.remove(index);
}
}
System.out.println(count);
尝试
出放:
2
反例:'values =“acxa”;和值2 =“阿巴达”;'预计'2'时返回'3'(如果重复不计数'1'预计) – 2014-10-02 10:39:14
@DmitryBychenko是的。 fixed.Thanks指出我 – 2014-10-02 10:51:16
可能重复http://*.com/questions/3985328/checking-if-2-strings-contain-the-same-characters – 2014-10-02 09:57:55
你遇到了什么问题,当你试图自己做这个? – EWit 2014-10-02 09:58:06
你试过了什么? – 2014-10-02 09:58:10