首页 > 其他 > 详细

LeetCode Wildcard Matching

时间:2015-11-10 13:49:05      阅读:262      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/wildcard-matching/

采用双指针,i为s的index, j为p的index.

若是当前对应字符match, 双双后移一位。若是不能match且p的当前字符是‘*‘, 就更新星号的starIndex 和 最后检查的位置lastCheck. 

当再次遇到不match时,j回到startIndex的后一位,lastCheck后一一位,i到lastCheck位上。

出了while loop 说明s到头了,看j是否到头即可。但是若当前j是‘*‘, 需要一致后移j.

Time Complexity is O(s.length() * p.length()). Space is O(1).

AC Java:

public class Solution {
    public boolean isMatch(String s, String p) {
        if(p.length() == 0){
            return s.length() == 0;
        }
        int starIndex = -1; //标记星号的index
        int lastCheck = -1; //标记上次检查的位置
        
        int i = 0; 
        int j = 0;
        while(i<s.length()){
            if(j<p.length() && isMatch(s.charAt(i), p.charAt(j))){
                i++;
                j++;
            }else if(j<p.length() && p.charAt(j) == ‘*‘){
                starIndex = j;
                lastCheck = i;
                j++;
            }else if(starIndex != -1){
                j = starIndex+1;
                lastCheck++;
                i=lastCheck;
            }else{
                return false;
            }
        }
        //s = "", p = "**"
        while(j<p.length() && p.charAt(j) == ‘*‘){
            j++;
        }
        return j == p.length();
    }
    
    private boolean isMatch(char s, char p){
        return p == ‘?‘ || s == p;
    }
}

Ref: http://www.cnblogs.com/icecreamdeqinw/p/4324962.html

LeetCode Wildcard Matching

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4952497.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!