Given String: This is Rajneesh This and will That is This
Required OUTPUT: This, is
---------------------------------------------------------
Source File: DuplicateString.java
package String_Programs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DuplicateString {
public static void duplicateString(String str){
Set<String> duplicateSet = new HashSet<String>()
List<String> duplicateList = new ArrayList<String>();
String[] strArray = str.split(" ");
for(int i=0;i<strArray.length;i++){
for(int j=i+1;j<strArray.length;j++){
if(strArray[i].equals(strArray[j])){
//if(duplicateList.contains(o))
duplicateSet.add(strArray[i]);
duplicateList.add(strArray[i]);
}
}
}
System.out.println("List bucket data :" +duplicateList);
System.out.println("Set bucket data :" +duplicateSet);
}
public static void main(String[] args) {
duplicateString("This is Rajneesh This and will That is This");
}
}
OUTPUT:
List bucket data :[This, This, is, This]
Set bucket data :[This, is]
The output between List and Set calls for a discussion. Have a look and try to figure out what's the difference?
Your Time complexity is O(n^2).
ReplyDeleteIt can be improved to O(n).