Most Asked Coding Problems on String in Java ?

I wanted to solve most asked interview coding problems using string data structure , so this guide will contain all the coding problems using string that I have solved.

1) How to find the maximum occurring character in a given String?

  public static void findMostRepeatedCharacter(String s) {

        HashMap<Character, Integer> map = new HashMap<>();

        char array[] = s.toCharArray();

        for (char c : array) {

            if (map.containsKey(c)) {
                // increment the count
                int valueReceived = map.get(c);
                map.put(c, ++valueReceived);
            }

            else {
                // give the count as 1

                map.put(c, 1);
            }

        }

        int maximum = Integer.MIN_VALUE;
        char mostRepeatedChar = ' ';

        for (Map.Entry entry : map.entrySet()) {

            // System.out.println(entry.getKey() + " " + entry.getValue());

            int currentValue = (int) entry.getValue();
            char currentKey = (char) entry.getKey();
            if (currentValue > maximum) {

                maximum = currentValue;
                mostRepeatedChar = currentKey;

            }
        }

        System.out.println(mostRepeatedChar + "   " + maximum);
    }
  1. Check whether the string are anagrams of each other or not ?

example :

SILENT and LISTEN

  • Sort both the string and then compare whether both are same or not
  public static void checkAnagram(String s1, String s2) {

        boolean flag = true;

        char s1Array[] = s1.toCharArray();

        char s2Array[] = s2.toCharArray();

        Arrays.sort(s1Array);
        Arrays.sort(s2Array);

        for (int i = 0; i < s2Array.length; i++) {

            if (s1Array[i] != s2Array[i]) {
                flag = false;
                break;
            }

        }
        System.out.println(flag);
    }
  • Approach2 : use a hashmap to store the key and value and then compare both are same

-Approach3 : use only single hashmap , one will increment the value other will decrement it at the last all values are 0 then it is anagram

-Approach 4 : create a variable sum and take the ASCII value of each of the character and then sum it do it for both the strings and then compare the ASCII value of the string it should be same.