[Leetcode] [JavaScript] Word Pattern

Source: Internet
Author: User

Word Pattern

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 substring 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.

The input str is matched to pattern patterns.

Need to open two hash tables, one is the pattern and STR mapping, there is a record pattern has not been used.

1 /**2 * @param {string} pattern3 * @param {string} str4 * @return {Boolean}5  */6 varWordpattern =function(pattern, str) {7     varDict = {}, used = {};8     varStrarr = Str.split (");9     if(Pattern.length!==strarr.length) {Ten         return false; One     } A      for(vari = 0; i < strarr.length; i++){ -         if(!Dict[strarr[i]]) { -             if(Used[pattern[i]]) { the                 return false; -}Else{ -Used[pattern[i]] =true; -             } +Dict[strarr[i]] =Pattern[i]; -}Else{ +             if(Dict[strarr[i]]!==Pattern[i]) { A                 return false; at             } -         } -     } -     return true; -};

[Leetcode] [JavaScript] Word Pattern

Related Article

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.