diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 006285eb..0aeeea66 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -72,6 +72,7 @@ 4. [Sequence](strings/sequence.java) 5. [Split String](strings/SplitString.java) 6. [Tokenizer](strings/tokenizer.java) +7. [Anagram](strings/anagram.java) ## Trees diff --git a/algorithms/Java/strings/anagram.java b/algorithms/Java/strings/anagram.java new file mode 100644 index 00000000..8f9554f9 --- /dev/null +++ b/algorithms/Java/strings/anagram.java @@ -0,0 +1,55 @@ +package Strings; + +import java.util.HashMap; + + +//Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. +//Return the minimum number of steps to make t an anagram of s. +//An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. + +public class anagram { + public static void main(String[] args) { + String s = "leetcode"; + String t = "practice"; + System.out.println(minSteps(s, t)); + System.out.println(minSteps2(s, t)); + + } + + + //1st solution + private static int minSteps(String s, String t) { + HashMap map = new HashMap<>(); + char[] charS = s.toCharArray(); + char[] charT = t.toCharArray(); + + for (int i = 0; i < charT.length; i++) { + map.put(i, charT[i]); + } + + for (char aChar : charS) { + if (map.containsValue(aChar)) { + map.values().remove(aChar); + } + } + + return map.size(); + } + + //2nd solution better and fast + private static int minSteps2(String s, String t) { + int n = s.length(); + int ans = 0; + int[] count = new int[26];//always keep in mind (26) when doing a string question + for (int i = 0; i < n; i++) { + count[s.charAt(i) - 'a']++; + count[t.charAt(i) - 'a']--; + } + for (int i = 0; i < 26; i++) { + if (count[i] > 0) + ans += count[i]; + } + return ans; + } +} +