Need a better way to find repeated words in a string

Viewed 138

I need a way to do the same operation with much less code. This will help me to understand Java in much better way. OUTPUT of the below code will be: new, boy, 3pm, to

public class substring {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost";
    String concant = "";
    int occurance =0;
    str = str.replaceAll(",", "");
    System.out.println(str);
    String[] subStr = str.split("\\s");
    for(String sub:subStr)
    {
        for (String sub1:subStr) {
            if(sub.equals(sub1))
            { 
                 occurance++;
                    
                if(occurance>=2)
                {
                    if(!concant.contains(sub))
                    {
                        if(concant!= "")
                          concant = concant +", "+ sub;
                        else
                            concant = sub;
                              
                    }
                }
            }
            
        }   
        occurance = 0;  
    }
    System.out.println(concant);
    
}

}
2 Answers

Solution

Instead of using nested loops you can take advantage of the functionality provided by a set data structure. A set is a collection that cannot contain duplicates. So by checking the truthiness of the add method you can determine duplicates

String[] listContainingDuplicates = "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost".split("[,\\s]+");
    
final LinkedHashSet<String> duplicates = new LinkedHashSet<String>(); 
final Set<String> temp = new HashSet<>();
    
for ( final String current : listContainingDuplicates ){
    if ( !temp.add( current ) )
        duplicates.add( current );
}
    
System.out.println( duplicates.toString() );

Treat this as pseudo code. There may be edge cases that you want to handle

Your solution has a time complexity of O(N^2) while the solution provided above runs in O(n)

Just split by spaces and group using streams, tthen filter these having less occurrences than two

String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost";
str = str.replaceAll(",", "");

List<String> duplicates = Arrays.stream(str.split(" "))
    .filter(s -> !s.isEmpty())
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    .entrySet()
    .stream()
    .filter(e -> e.getValue() > 1)
    .map(e -> e.getKey())
    .collect(Collectors.toList());
    
Related