Leetcode:word Pattern

Source: Internet
Author: User

Given a pattern and a string str, findifSTR follows the same pattern. Here follow means a full match, such that there was a bijection between a letter in pattern and a non-empty word in Str. Examples:pattern= "ABBA", str = "Dog cat Cat Dog" shouldreturn true. Pattern= "ABBA", str = "Dog cat cat Fish" shouldreturn false. Pattern= "AAAA", str = "Dog cat Cat Dog" shouldreturn false. Pattern= "ABBA", str = "dog dog Dog" shouldreturn false. Notes:you assume pattern contains only lowercase letters, and STR contains lowercase letters separated by a single spa CE.

Note that this is a one by one mapping, that is, if the A->dog, B->dog, should return false, so should be on the basis of HashMap to add a layer of check, even if does not contain the key, before adding the map should check Map.values (). Contains (String)

1  Public classSolution {2      Public BooleanWordpattern (string pattern, string str) {3         if(pattern==NULL|| str==NULL)return false;4string[] all = Str.split ("");5         6         if(Pattern.length ()! = all.length)return false;7Hashmap<character, string> map =NewHashmap<character, string>();8          for(inti=0; I<pattern.length (); i++) {9             if(!Map.containskey (Pattern.charat (i))) {Ten                 if(Map.values (). Contains (All[i]))return false; One Map.put (Pattern.charat (i), all[i]); A             } -             Else { -                 if(!Map.get (Pattern.charat (i)). Equals (All[i] ) the                     return false; -             } -         } -         return true; +     } -}

Leetcode:word Pattern

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.