The Oracle (N ^ 2) TLE written in brute force mode is used before this question. Use Hashtable to write it.
Package Level3; import java. util. arrayList; import java. util. arrays; import java. util. hashtable; import java. util. set;/*** Anagrams * Given an array of strings, return all groups of strings that are anagrams. note: All inputs will be in lower-case. **/public class S49 {public static void main (String [] args) {} public ArrayList <String> anagrams (String [] strs) {ArrayList <String> ret = new Arra YList <String> (); // uses the sorted string as the key, and its ansible is used as the ArrayList Hashtable <String, ArrayList <String> ht = new Hashtable <String, arrayList <String> (); for (int I = 0; I <strs. length; I ++) {String sorted = sorted (strs [I]); ArrayList <String> val = ht. get (sorted); if (val! = Null) {val. add (strs [I]);} else {val = new ArrayList <String> (); val. add (strs [I]); ht. put (sorted, val) ;}/// keySet Set <String> set = ht. keySet (); // Add all anchor to ret for (String s: set) {ArrayList <String> val = ht. get (s); if (val. size ()> 1) {ret. addAll (val) ;}} return ret;} public String sorted (String a) {char [] achar =. toCharArray (); Arrays. sort (achar); return new String (achar );}}
The question is to give a String array to find words consisting of the same letters. For example: S = ["abc", "bca", "bac", "bbb", "bbca", "abcb"] the answer is: ["abc ", "bca", "bac", "bbca", "abcb"] Only "bbb" does not contain words of the same letter.