Java examples for java.lang:String Algorithm
check Anagram
//package com.java2s; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] argv) throws Exception { String str_one = "java2s.com"; String str_two = "java2s.com"; checkAnagram(str_one, str_two);// www . j a va 2 s.co m } public static void checkAnagram(final String str_one, final String str_two) { int flag = 1; new Scanner(System.in); /* * System.out.println("Enter first string, second string: "); String str = scan_it.nextLine(); String * []strArr = str.split(","); */ /* * String str1 = strArr[0].trim(); String str2 = strArr[1].trim(); */ final String str1 = str_one; final String str2 = str_two; final HashMap<Character, Integer> map = new HashMap<Character, Integer>(); char c; for (int i = 0; i < str1.length(); i++) { c = str1.charAt(i); if (map.get(c) != null) { map.put(c, map.get(c + 1)); } else { map.put(str1.charAt(i), 1); } } /* * for(int j = 0; j < str2.length(); j++){ if(map.containsKey(str2.charAt(j))) map.put(str2.charAt(j), * map.get(str2.charAt(j))-1); else flag = 0; } */ for (int j = 0; j < str2.length(); j++) { if (map.containsKey(str2.charAt(j))) { map.put(str2.charAt(j), map.get(str2.charAt(j)) + 1); } else { flag = 0; } } /* * for(Integer k : map.values()) if(k !=0 ) flag = 0; */ for (final Integer k : map.values()) if ((k % 2) != 0) { flag = 0; } if (flag == 1) { System.out.println("Anagram"); } else { System.out.println("Nt Anagram."); } } }