10. Regular Expression Matching(hard)

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Note:

s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:

Input:
s = "aa"
p = "a"
Output: true
Explanation: '
' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:

Input:
s = "ab"
p = "."
Output: true
Explanation: ".
" means "zero or more (*) of any character (.)".
Example 4:

Input:
s = "aab"
p = "cab"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
Example 5:

Input:
s = "mississippi"
p = "misisp*."
Output: false

分析:

Java语言:

public static boolean isMatch(String s, String p) {
        if (p.isEmpty()) {
            return s.isEmpty();
        }
        boolean firstMatch = !s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.');
        if (p.length() >= 2 && p.charAt(1) == '*') {
            return isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p));
        } else {
            return firstMatch && isMatch(s.substring(1), p.substring(1));
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 2019.3.12 晴 星期二 今天是日记星球第30期开学典礼的日子。 回想加入日记星球刚开始的激情,每次看同...
    冯世琴阅读 197评论 2 4
  • 偏爱是真的可以为所欲为的,就像老师叫自己喜欢的同学回答问题答不上来老师也是笑眯眯的。 而我对你的大概也是叫偏爱,我...
    给我明灯阅读 343评论 0 4
  • 今天有妈妈带着小朋友从北京来找女儿玩,到我们家的时候已经快十点了,去市里玩有点晚,于是决定就在大鹏附近玩。 大鹏附...
    凤舞清林阅读 258评论 1 1