【leetcode刷题笔记】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


题解:昨天晚上写了一晚上的递归,一直TLE。早上果断改用dp了,结果dp还TLE了好多次,真是说多了都是泪。

dp的思想很简单:用二维数组dp[s_length+1][p_length+1]记录结果。

  • 首先如果s和p都是空串的话,那么它们是匹配的,所以dp[0][0] = true;
  • 当s为空串的时候(dp中的第一行),dp[0][i] = p[i] == ‘*‘? dp[0][i-1]:false;(i=1,...,p_length);
  • 对于任意j,如果p(j-1) == ‘*‘,dp[i][j]= dp[i-1][j] || dp[i][j-1],对应了两种情况,前一种是不匹配‘*’,后一种情况是匹配‘*‘,如下图所示:
  • 如果p(j-1) != ‘*‘,则只有p(j-1) == ‘?‘或者s(i-1) == p(j-1)的时候才有dp[i][j] = true;否则dp[i][j] = false;

开始以为这样就可以过了,事实证明I am too young too simple。这样还是会超时。要优化两个地方:

  • 数出p中不是‘*‘的字符个数,如果比s的总长度还长,那么s是没有办法匹配的,直接返回false;
  • 第二个优化让我非常无语,就是在实现循环的时候,不要每次用p.charAt(j)来取字符,要在开始用ch_p = p.charAt(j)把字符记下来,在以后的循环中就用这个,这么看来p.charAt(j)这个操作还是很耗时的,以后如果在程序中反复使用,都要把它存下来再使用。

最后AC的代码如下:

 1 public class Solution {
 2     public boolean isMatch(String s, String p) {
 3         int m = s.length();
 4         int n = p.length();
 5
 6         int count = 0;
 7         for(int indexP = 0;indexP<n;indexP++)
 8             if(p.charAt(indexP) != ‘*‘)
 9                 count++;
10         if(count > m)
11             return false;
12
13         boolean[][] dp =new boolean[m+1][n+1];
14         dp[0][0] = true;
15
16         for(int j = 1;j<=n;j++)
17         {
18             char ch_p = p.charAt(j-1);
19             if(ch_p ==‘*‘ && dp[0][j-1])
20                 dp[0][j]= true;
21
22             for(int i= 1;i<=m;i++){
23                 char ch_s = s.charAt(i-1);
24                 if(ch_p ==‘*‘)
25                     dp[i][j]= dp[i-1][j]|| dp[i][j-1];
26                 else if(ch_p == ‘?‘ || ch_p == ch_s){
27                     dp[i][j] = dp[i-1][j-1];
28                 }
29                 else
30                     dp[i][j]= false;
31             }
32         }
33         return dp[m][n];
34     }
35 }

【leetcode刷题笔记】Wildcard Matching

时间: 2024-10-14 00:39:30

【leetcode刷题笔记】Wildcard Matching的相关文章

【leetcode刷题笔记】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

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的