Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《程序员面试金典(第 6 版)》16.18. 模式匹配 #226

Open
Tcdian opened this issue Jun 22, 2020 · 1 comment
Open

《程序员面试金典(第 6 版)》16.18. 模式匹配 #226

Tcdian opened this issue Jun 22, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 22, 2020

《程序员面试金典(第 6 版)》16.18. 模式匹配

你有两个字符串,即patternvaluepattern字符串由字母"a""b"组成,用于描述字符串中的模式。例如,字符串"catcatgocatgo"匹配模式"aabab"(其中"cat""a""go""b"),该字符串也匹配像"a""ab""b"这样的模式。但需注意"a""b"不能同时表示相同的字符串。编写一个方法判断value字符串是否匹配pattern字符串。

Example 1

输入: pattern = "abba", value = "dogcatcatdog"
输出: true

Example 2

输入: pattern = "abba", value = "dogcatcatfish"
输出: false

Example 3

输入: pattern = "aaaa", value = "dogcatcatdog"
输出: false

Example 4

输入: pattern = "abba", value = "dogdogdogdog"
输出: true
解释: "a"="dogdog",b="",反之也符合规则

Note

  • 0 <= len(pattern) <= 1000
  • 0 <= len(value) <= 1000
  • 你可以假设pattern只包含字母"a""b"value仅包含小写字母。
@Tcdian Tcdian added the String label Jun 22, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 22, 2020

Solution

  • TypeScript Solution
function patternMatching(pattern: string, value: string): boolean {
    if (pattern === '') {
        return value === '';
    }
    let p = '^';
    let aPattern = '';
    let bPattern = '';
    for (let i = 0; i < pattern.length; i++) {
        if (pattern[i] === 'a') {
            if (aPattern === '') {
                p += '([a-z]*)';
                aPattern = bPattern === '' ? '\\1' : '\\2';
            } else {
                p += aPattern;
            }
        } else if (pattern[i] === 'b') {
            if (bPattern === '') {
                p += '([a-z]*)';
                bPattern = aPattern === '' ? '\\1' : '\\2'; 
            } else {
                p += bPattern;
            }
        }
    }
    p += '$';
    let result = false;
    const match = value.match(new RegExp(p));
    if (match) {
        const [, aGroup, bGroup] = match;
        result = aGroup !== bGroup;
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant