java - 需要一种更好的方法来查找字符串中的重复单词

标签 java

我需要一种方法来用更少的代码完成同样的操作。这将帮助我更好地理解 Java。 以下代码的输出将是: 新的,男孩,下午 3 点,到

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);
    
}

}

最佳答案

解决方案

您可以利用集合数据结构提供的功能,而不是使用嵌套循环。集合是不能包含重复项的集合。因此,通过检查 add 方法的真实性,您可以确定重复项

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

您的解决方案的时间复杂度为 O(N^2),而上面提供的解决方案的运行时间复杂度为 O(n)

关于java - 需要一种更好的方法来查找字符串中的重复单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66606102/

相关文章:

java - MedianCalc() 方法给我 IndexOutOfBounds 异常

java - 使用套接字将 .jpg 从 Android 发送到 C++

java - 如何使用 Spring Boot Gradle 插件和 bootJar 任务有条件地排除 java 文件?

java - 如何给字符串中的变量赋值?

java - 从 JSON 响应中获取一半数据

java - 如何增加 eclipse 中的 jboss 内存堆大小

java - j_security_check之前执行的过滤器

java - 使用 XML onClick 时出现 Android Dialog NoSuchMethodException 错误

java - 将 Java 与模块一起使用

java - 单击鼠标时程序不执行功能