Regex匹配

來源:互聯網
上載者:User

標籤:[]   第一個   public   出現   ||   一個   int   返回   bsp   

題目描述請實現一個函數用來匹配包括‘.‘和‘*‘的Regex。模式中的字元‘.‘表示任意一個字元,而‘*‘表示它前面的字元可以出現任意次(包含0次)。 在本題中,匹配是指字串的所有字元匹配整個模式。例如,字串"aaa"與模式"a.a"和"ab*ac*a"匹配,但是與"aa.a"和"ab*a"均不匹配注意:&&的優先順序高於||
當模式中的第二個字元不是“*”時:1、如果字串第一個字元和模式中的第一個字元相匹配,那麼字串和模式都後移一個字元,然後匹配剩餘的。2、如果 字串第一個字元和模式中的第一個字元相不匹配,直接返回false。  而當模式中的第二個字元是“*”時:如果字串第一個字元跟模式第一個字元不匹配,則模式後移2個字元,繼續匹配。如果字串第一個字元跟模式第一個字元匹配,可以有3種匹配方式:1、模式後移2字元,相當於x*被忽略;2、字串後移1字元,模式後移2字元;3、字串後移1字元,模式不變,即繼續匹配字元下一位,因為*可以匹配多位; public class Solution {    public boolean match(char[] str, char[] pattern) {    if (str == null || pattern == null) {        return false;    }    int strIndex = 0;    int patternIndex = 0;    return matchCore(str, strIndex, pattern, patternIndex);}  public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {    //有效性檢驗:str到尾,pattern到尾,匹配成功    if (strIndex == str.length && patternIndex == pattern.length) {        return true;    }    //pattern先到尾,匹配失敗    if (strIndex != str.length && patternIndex == pattern.length) {        return false;    }    //模式第2個是*,且字串第1個跟模式第1個匹配,分3種匹配模式;如不匹配,模式後移2位    if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == ‘*‘) {        if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == ‘.‘ && strIndex != str.length)) {            return matchCore(str, strIndex, pattern, patternIndex + 2)//模式後移2,視為x*匹配0個字元                    || matchCore(str, strIndex + 1, pattern, patternIndex + 2)//視為模式比對1個字元                    || matchCore(str, strIndex + 1, pattern, patternIndex);//*匹配多個,再匹配str中的下一個        } else {            return matchCore(str, strIndex, pattern, patternIndex + 2);        }    }    //模式第2個不是*,且字串第1個跟模式第1個匹配,則都後移1位,否則直接返回false    if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == ‘.‘ && strIndex != str.length)) {        return matchCore(str, strIndex + 1, pattern, patternIndex + 1);    }    return false;    }}

Regex匹配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.