Anagrams @ LeetCode

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.