Intersection of two strings in Java

2019-01-09 01:32发布

Need a Java function to find intersection of two strings. i.e. characters common to the strings.

Example:

String s1 = new String("Sychelless");
String s2 = new String("Sydney");

9条回答
成全新的幸福
2楼-- · 2019-01-09 01:53

Most basic approach:

String wordA = "Sychelless";  
String wordB = "Sydney";  
String common = "";  

for(int i=0;i<wordA.length();i++){  
    for(int j=0;j<wordB.length();j++){  
        if(wordA.charAt(i)==wordB.charAt(j)){  
            common += wordA.charAt(i)+" ";  
            break;
        }  
    }  
}  
System.out.println("common is: "+common);  
查看更多
forever°为你锁心
4楼-- · 2019-01-09 01:57

I have used TreeSet. And retainAll() in TreeSet to get matched elements.

Oracle Doc:

retainAll(Collection<?> c)

Retains only the elements in this set that are contained in the specified collection (optional operation).

String s1 = new String("Sychelless");
String s2 = new String("Sydney");

Set<Character> firstSet = new TreeSet<Character>();
for(int i = 0; i < s1.length(); i++) {
    firstSet.add(s1.charAt(i));
}

Set<Character> anotherSet = new TreeSet<Character>();
for(int i = 0; i < s2.length(); i++) {
    anotherSet.add(s2.charAt(i));
}

firstSet.retainAll(anotherSet);
System.out.println("Matched characters are " + firstSet.toString());//print common strings

//output > Matched characters are [S, e, y]
查看更多
对你真心纯属浪费
5楼-- · 2019-01-09 01:58

Extract the characters

String.toCharArray

Put them in a Set Find the intersection

Set.retainAll
查看更多
【Aperson】
6楼-- · 2019-01-09 02:02

I think the algorithm you are looking for is the problem of the longest common subsequence

查看更多
叛逆
7楼-- · 2019-01-09 02:03

By means of Guava this task seems much easier:

String s1 = new String("Sychelless");
String s2 = new String("Sydney");
Set<String> setA = Sets.newHashSet(Splitter.fixedLength(1).split(s1));
Set<String> setB = Sets.newHashSet(Splitter.fixedLength(1).split(s2));
Sets.intersection(setA, setB);
查看更多
登录 后发表回答