Posts

Showing posts from May, 2020

Find all the permutations of a string - similar to permute arrays

Image
Recursive Solution Example String: abcdefgh When i = 0, we have, First wave of recursion till the String is empty Input String: abcdefgh - ""  +  "bcdefgh" = "bcdefgh" Input String: bcdefgh - ""  +  "cdefgh"    = "cdefgh" Input String: cdefgh - ""  +  "defgh"       = "defgh" Input String: defgh - ""  +  "efgh"           = "efgh" Input String: efgh - ""  +  "fgh"               = "fgh" Input String: fgh - ""  +  "gh"                  = "gh" Input String: gh - ""  +  "h"                     = "h" Input String: h - ""  +  ""                         = "" Then coming out of recursion Input String: gh - "g"  +  "" = "g" Input String: g - ""...

Find the maximum occurring character in given String ?

public static void main(String[] args) { System.out.println(maxOccurringChar("122333444455555666666")); } public static Character maxOccurringChar(String s) { Map<Character, Integer> charCountMap = new HashMap<>(); char[] array = s.toCharArray(); for (int i = 0; i < array.length; i++) { if(array[i] != ' ') { Integer occ = charCountMap.getOrDefault(array[i], 0); charCountMap.put(array[i], ++occ); } } Map.Entry<Character, Integer> maxEntry = charCountMap.entrySet().stream() .max(Map.Entry.comparingByValue()).get(); // Map.Entry<Character, Integer> maxEntry = getEntryWithMaxValue(charCountMap); System.out.println(String.format("Character %s occurs %s times.", maxEntry.ge...

Find if the String is a number or floating point number - Regular Expression

Find if a string contains only digits? public static boolean stringContainsOnlyDigits(String s) { Pattern p = Pattern.compile( "^[0-9]+$" ); Matcher m = p.matcher( s ); return m.find(); } Find if the String is a Floating Point number. public static boolean stringIsFloatingPointNumber(String s) { Pattern p = Pattern.compile( "^[-+]?[0-9]*\\.?[0-9]+$" ); Matcher m = p.matcher( s ); boolean found = m.find(); if(found) { System.out.println("found: " + m.group(0)); } return found; } The caveat here is the strings are long text and Double.parseDouble() will be out of range. Such problems can be solved only using Regular Expressions .