Java
Program to find Repeated Characters of String:-
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Exception {
Scanner
scanner = new Scanner(System.in);
String
str = scanner.nextLine();
System.out.println(str);
new
Test().printDuplicateChar(str);
scanner.close();
}
private void printDuplicateChar(String str){
Map<Character,
Integer> dataMap = new HashMap<>();
char[] chars = str.toCharArray();
for(Character ch : chars) {
dataMap.put(ch, dataMap.containsKey(ch) ? dataMap.get(ch)+1 : 1);
}
dataMap.entrySet().stream().forEach(map -> {
if(map.getValue() > 1) {
System.out.println("duplicate
char :: "+map.getKey()+" occurence is "+map.getValue());
}
});
}
}
In above code we saving the string into HashMap character
as key and occurrence as integer, here we iterate the string store into the map
and print all elemnt whose occurrence is more than 1, complexity of above code
in O(N).
Check
whether a string is anagram:-
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Exception {
Scanner
scanner = new Scanner(System.in);
String
one = scanner.next();
String
two = scanner.next();
System.out.println(new Test().checkAnagram(one, two));
scanner.close();
}
public boolean checkAnagram(String one, String two) {
if(!(one.length() == two.length())) {
return false;
}
char[] chArray = one.toCharArray();
for(char ch : chArray) {
if(two.replace(ch+"", "").isEmpty()); {
return true;
}
}
return false;
}
}
Print all substrings of a given
string
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Exception {
Scanner
scanner = new Scanner(System.in);
String
one = scanner.next();
new
Test().printAllSubString(one);
scanner.close();
}
private void printAllSubString(String one) {
for (int i = 0; i < one.length(); i++) {
for (int j = i; j <= one.length(); j++) {
if (i != j) {
System.out.println(one.substring(i, j));
}
}
}
}
}
}
interview question, well explained
ReplyDelete