我需要一种方法来用更少的代码完成同样的操作。这将帮助我更好地理解 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/