[LeetCode]44. Wildcard Matching

来源:互联网 发布:房产中介软件hao123 编辑:程序博客网 时间:2024/05/29 09:43

https://leetcode.com/problems/wildcard-matching/




这里面要处理的就是*,如果遇到*,那么用matchIdx记录已经匹配的str位置,starIdx表示*所在位置。当遇到*时,最开始让*表示0个str里面的字符,所以p++;之后再匹配,如果s和p有匹配不上,那么让*表示一个字符,之后依次类推。

public class Solution {    public boolean isMatch(String str, String pattern) {        int s = 0;        int p = 0;        int starIdx = -1;        int matchIdx = 0;        while (s < str.length()) {            if (p < pattern.length() && (str.charAt(s) == pattern.charAt(p) || pattern.charAt(p) == '?')) {                s++;                p++;            } else if (p < pattern.length() && pattern.charAt(p) == '*') {                matchIdx = s;                starIdx = p;                p++;            } else if (starIdx != -1) {                // 使用match++ & sIndex = match而不是直接sIndex = match + 1是因为如果后续所有s和p均不匹配,sIndex可以一直自增,而不是死循环                s = ++matchIdx;                p = starIdx + 1;            } else {                return false;            }        }        while (p < pattern.length() && pattern.charAt(p) == '*') {            p++;        }        return p == pattern.length();    }}


0 0
原创粉丝点击