290. Word Pattern Java Solutions

Source: Internet
Author: User

Given a pattern and a string str , find if str follows the same pattern.

Here follow means a full match, such that there was a bijection between a letter in and pattern a non-empty word in str .

Examples:

    1. pattern = "abba" , str = "dog cat cat dog" should return true.
    2. pattern = "abba" , str = "dog cat cat fish" should return FALSE.
    3. pattern = "aaaa" , str = "dog cat cat dog" should return FALSE.
    4. pattern = "abba" , str = "dog dog dog dog" should return FALSE.

Notes:
Assume contains only pattern lowercase letters, and contains lowercase letters separated by str a single space.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

1  Public classSolution {2      Public BooleanWordpattern (string pattern, string str) {3Hashmap<character, string> HM =NewHashmap<character, string>();4Set<string> set =NewHashset<string>();5string[] arr = Str.split ("");6         if(Arr.length! = Pattern.length ())return false;7          for(intI =0;i< pattern.length (); i++){8             if(Hm.get (Pattern.charat (i))! =NULL){9                 if(!hm.get (Pattern.charat (i)). Equals (Arr[i]))return false;Ten}Else{ One                 if(Set.contains (Arr[i]))return false; A                 Else{ - Hm.put (Pattern.charat (i), arr[i]); - Set.add (Arr[i]); the                 } -             } -         } -         return true; +          -     } +}

290. Word Pattern Java Solutions

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.