444. Wildcard Matching

 

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

這題分三步驟,第一步驟就是最單純的一個一個比

然後才是難點處理  *  ,因為不知道他到底會對齊到哪一位

所以這邊就用了一個 s_star 來記錄 實際 * 到底代表了幾位

也因此第三部分處理的就是,當發現對不齊的時候,試著把 s_star 拉長再對齊看看

 

然後注意 * 可以代表空字元,所以在寫遇到*的時候

s_index 可以不用也跟著前進,只有p_index+1

 

第一個while迴圈是試著走過全部的s ,不過因為p 可能也會有剩的*,而這也會是合理的解,所以第二個while迴圈是在處理這個

class Solution {
    public boolean isMatch(String s, String p) {
        int s_index=0, p_index=0, p_star=-1, s_star=-1;
        while(s_index < s.length()){
            if((p_index < p.length()) && ((p.charAt(p_index) == '?')||(s.charAt(s_index) == p.charAt(p_index)))) {
                s_index++; p_index++;
                continue;
            }
            if((p_index < p.length()) && (p.charAt(p_index) == '*')) {
                p_star = p_index++;
                s_star = s_index;
                continue;
            }
            if(p_star >= 0){
                p_index = p_star+1;
                s_index = ++s_star;
                continue;
            }
            return false;
        }
        while(p_index < p.length() && p.charAt(p_index) == '*')
            p_index++;
        return (p_index == p.length());
    }
}

 

arrow
arrow
    全站熱搜

    angledark0123 發表在 痞客邦 留言(0) 人氣()