Leetcode 290. Word Pattern

Source: Internet
Author: User

290. Word PatternTotal accepted:42115Total submissions:140014 difficulty:easy

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.

Idea: Mapping. Refer to Leetcode 205 for details. The first method of isomorphic strings

Code:

Note the usage of Istringstream, header file <sstream>. This can be used specifically to break down strings that contain spaces .

1 classSolution {2  Public:3     BOOLWordpattern (stringPatternstringstr) {4map<Char,int>P2i;5map<string,int>s2i;6         stringtemp;7         intI=0, n=pattern.size ();8Istringstreaminch(str);9          while(inch>>temp) {Ten             if(i<N) { One                 //there is no corresponding key-value pair in map, 0 is returned A                 if(p2i[pattern[i]]!=S2i[temp]) { -                     return false; -                 } thep2i[pattern[i]]=s2i[temp]=i+1; -             } -i++; -         } +         returni==N; -     } +};

Leetcode 290. 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.