zoukankan      html  css  js  c++  java
  • 剑指offer之【正则表达式】☆

    题目:

      正则表达式匹配

    链接:

      https://www.nowcoder.com/practice/45327ae22b7b413ea21df13ee7d6429c?tpId=13&tqId=11205&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

      请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

    思路: 

      当模式中的第二个字符不是“*”时:
        1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的。
        2、如果 字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
     
      而当模式中的第二个字符是“*”时:
      如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
        1、模式后移2字符,相当于x*被忽略;
        2、字符串后移1字符,模式后移2字符;
        3、字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;
    代码:
      
     1 class Solution{
     2 public:
     3     bool match(char* str, char* pattern){
     4         if(*str == '' && *pattern == ''){
     5             return true;
     6         }
     7         if(*pattern == ''){
     8             return false;
     9         }
    10         if(*(pattern+1) == '*'){
    11             if(*pattern == *str || (*pattern == '.' && *str != '')){
    12                 return match(str,pattern+2) || match(str+1,pattern+2) || match(str+1,pattern);
    13             }else{
    14                 return match(str,pattern+2);
    15             };
    16         };
    17         if(*pattern == *str || (*pattern == '.'&& *str != '')){
    18             return match(str+1,pattern+1);
    19         }
    20         return false;    
    21     }
    22 };
  • 相关阅读:
    angular $modal 模态框
    过滤器 ||(filter)
    info sharp Are you trying to install as a root or sudo user? Try again with the --unsafe-perm flag
    git error: unable to create file Invalid argument
    bash shell 快捷键
    options has an unknown property 'modifyVars'. These properties are valid: 处理方法
    test 分支强制替换master 分支的办法
    脚本统计代码行数
    git commit 后,没有push ,怎么撤销
    php 用户ip的获取
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6970545.html
Copyright © 2011-2022 走看看