The assignment is to remove the repeating string from a given string and get the count of repeated string.
The code I have tried is below :
public static void main(String[] args) {
String longString = "Energy in the form of seismic waves is released " +
"after an earthquake and seismometers measure its amplitude to calculate the " +
"quake's intensity. For a long time, earthquakes were measured on the Richter scale." +
" Since the scale was based on conditions in California and was not reliable in measuring large earthquakes," +
" it was replaced by a 'moment magnitude' scale in the 1970s";
// replace the special characters
String freeString = longString.replaceAll("[^\\w\\s-]", "");
//the new string is
System.out.println("freeString :: " + freeString);
//Calculate the length of the string
String[] countOfString = freeString.split(" ");
System.out.println("countOfString :: " + countOfString.length);
Set<String> uniqueString = new HashSet<String>();
Map<String, Integer> countMap = new HashMap<String, Integer>();
for (int i = 0; i < countOfString.length; i++) {
String tempString = countOfString[i];
if(!uniqueString.contains(tempString)){
uniqueString.add(tempString);
}else{
if(!countMap.containsKey(tempString)){
countMap.put(tempString, 1);
}else{
Integer count = countMap.get(tempString);
count++;
countMap.put(tempString, count);
}
System.out.println("found the repeating string " + tempString);
}
}
//remove the repeating string set from the uniqueString set
uniqueString.removeAll(countMap.keySet());
System.out.println("the repeating string " + countMap);
System.out.println("the set has the uniuqe strings " + uniqueString);
System.out.println("the set has the uniuqe strings of length " + uniqueString.size());
}
Is there any best way/approach other than this? Will this code work for very large string (e.g. parsing the text of a book) Will it have any performance issue?