首页 > 代码库 > Regular Expression Matching
Regular Expression Matching
Implement regular expression matching with support for ‘.‘
and ‘*‘
.
‘.‘ Matches any single character. ‘*‘ Matches zero or more of the preceding element. 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", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true
答案
public class Solution { public boolean match(char s,char p) { return s==p||p=='.'; } public boolean isMatch(String s, String p) { int sLen = s.length(); int pLen = p.length(); int i; int j; int k; boolean[][] match = new boolean[sLen+1][pLen+1]; match[0][0]=true; for(i=0;i<sLen;i++) { match[i+1][0]=false; } for(j=0;j<pLen;j++) { if(p.charAt(j)=='*') { match[0][j+1]=match[0][j-1]; } else { match[0][j+1]=false; } } for (i = 0; i < sLen; i++ ) { for (j = 0; j < pLen; j++ ) { if (p.charAt(j) == '*') { //0个、1个或多个 match[i+1][j+1]=match[i+1][j-1]||match[i+1][j]||(match(s.charAt(i),p.charAt(j-1))&&match[i][j+1]); } else { match[i+1][j+1]=match(s.charAt(i),p.charAt(j))&&match[i][j]; } } } return match[sLen ][pLen ]; } }
Regular Expression Matching
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。