LeetCode 44 Wildcard Matching 贪心 DP

本文介绍了一种实现通配符匹配的算法,该算法支持 '?' 和 '*' 两种通配符,其中 '?' 可以匹配任意单个字符,而 '*' 可以匹配任意长度的字符序列。文中提供了贪婪算法及动态规划算法的实现,并通过多个实例验证了算法的有效性。

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

--------------------------------------------------

Greedy Solution:

1. There is no need to refresh the status of star, staremerge. Only one star is enough, because the character(for example, 'a') always needs to match some 'a' in s. Matching the former 'a' is better than the latter 'a' in s as is illustrated in the figure. I.e., there is no need to record the matching range for every '*', the latest '*' has the largest range of choice. 

2. sbegin is refreshed when mismatch occurs and pbegin is refreshed when meeting new '*';

3. Focusing on s is better than handling the two strings at the same time. 

So the final concise code is like:

class Solution:
    def isMatch(self, s, p):
        slen, plen, i, j = len(s), len(p), 0, 0
        star = False
        while (i < slen):
            if (j < plen and (s[i] == p[j] or p[j] == '?')):
                i += 1
                j += 1
            elif (j < plen and p[j] == '*'):
                star_begin_s = i
                star_begin_p = j+1
                j += 1
                star = True
            elif (star):
                j = star_begin_p
                star_begin_s += 1
                i = star_begin_s
            else:
                return False
        while (j < plen and p[j] == '*'):
            j += 1
        if (j == plen):
            return True
        return False

Using DP, the codes look like:

class Solution {
 public:
  bool isMatch(const char *s, const char *p) {
    int slen = strlen(s), plen = strlen(p), i, j, countp = 0;
    for (const char *ptr = p; *ptr; ++ptr)
      if (*ptr != '*')
        ++countp;
    if (countp > slen)
      return false;
    bool dp[500][500];
    memset(dp,false,sizeof(dp));
    dp[0][0] = true;
    for (i = 1; i <= plen; ++i) {
      dp[i][0] = dp[i - 1][0] && *(p + i -1) == '*';
      for (j = 1; j <= slen; ++j) {
        if (*(p + i -1) == '*')
          dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
        else
          dp[i][j] = dp[i - 1][j - 1] && (*(p + i -1) == *(s + j -1) || *(p + i -1) == '?');
      }
    }
    return dp[plen][slen];
  }
};

DP Solution:

f[i][j] indicates whether p[0..i] matches s[0..j]. So 

if p[i] == '*', dp[i][j] = dp[i][j-1] || dp[i-1][j]

if p[i] != '*', dp[i][j] = dp[i-1][j-1] && single match

reduce two-dimension dp to 1 dimension

class Solution:
    def isMatch(self, s, p):
        slen, plen = len(s), len(p)
        if (plen <= 0):
            return slen == 0
        if (slen <= 0):
            return all(pi == '*' for pi in p)

        f = [p[0] == '*' for i in range(slen)]
        f[0] = (p[0] == '*' or p[0] == s[0] or p[0] == '?')

        match_empty = [False for i in range(plen)] #以i结尾的p是否和s的空前缀匹配
        match_empty[0] = p[0] == '*'
        for i in range(1, plen):
            match_empty[i] = (match_empty[i-1] and p[i] == '*')
        #print(f)
        for i in range(1, plen):
            pre = list(f)
            for j in range(0, slen):
                if (p[i] == '*'):
                    #f[i][j] = f[i][j-1] || f[i-1][j]
                    tmp2 = f[j-1] if j >= 1 else match_empty[i-1]
                    f[j] = f[j] or tmp2
                else:
                    #f[i][j] = f[i-1][j-1]
                    match = (p[i] == s[j]) or (p[i] == '?')
                    tmp = pre[j-1] if j >= 1 else match_empty[i-1]
                    f[j] = tmp and match
            #print(f)

        return f[-1]
s = Solution()
print(s.isMatch("aa","a"))
print(s.isMatch("aa","aa"))
print(s.isMatch("aaa","a"))
print(s.isMatch("aa","*"))
print(s.isMatch("aa","a*"))
print(s.isMatch("ab","?*"))
print(s.isMatch("aab","c*a*b"))
print(s.isMatch("adceb","*a*b"))
print(s.isMatch("a","a*"))

 

C语言-光伏MPPT算法:电导增量法扰动观察法+自动全局搜索Plecs最大功率跟踪算法仿真内容概要:本文档主要介绍了一种基于C语言实现的光伏最大功率点跟踪(MPPT)算法,结合电导增量法与扰动观察法,并引入自动全局搜索策略,利用Plecs仿真工具对算法进行建模与仿真验证。文档重点阐述了两种经典MPPT算法的原理、优缺点及其在不同光照和温度条件下的动态响应特性,同时提出一种改进的复合控制策略以提升系统在复杂环境下的跟踪精度与稳定性。通过仿真结果对比分析,验证了所提方法在快速性和准确性方面的优势,适用于光伏发电系统的高效能量转换控制。; 适合人群:具备一定C语言编程基础和电力电子知识背景,从事光伏系统开发、嵌入式控制或新能源技术研发的工程师及高校研究人员;工作年限1-3年的初级至中级研发人员尤为适合。; 使用场景及目标:①掌握电导增量法与扰动观察法在实际光伏系统中的实现机制与切换逻辑;②学习如何在Plecs中搭建MPPT控制系统仿真模型;③实现自动全局搜索以避免传统算法陷入局部峰值问题,提升复杂工况下的最大功率追踪效率;④为光伏逆变器或太阳能充电控制器的算法开发提供技术参考与实现范例。; 阅读建议:建议读者结合文中提供的C语言算法逻辑与Plecs仿真模型同步学习,重点关注算法判断条件、步长调节策略及仿真参数设置。在理解基本原理的基础上,可通过修改光照强度、温度变化曲线等外部扰动因素,进一步测试算法鲁棒性,并尝试将其移植到实际嵌入式平台进行实验验证。
【无人机协同】动态环境下多无人机系统的协同路径规划与防撞研究(Matlab代码实现)​ 内容概要:本文围绕动态环境下多无人机系统的协同路径规划与防撞问题展开研究,提出基于Matlab的仿真代码实现方案。研究重点在于在复杂、动态环境中实现多无人机之间的高效协同飞行与避障,涵盖路径规划算法的设计与优化,确保无人机集群在执行任务过程中能够实时规避静态障碍物与动态冲突,保障飞行安全性与任务效率。文中结合智能优化算法,构建合理的成本目标函数(如路径长度、飞行高度、威胁规避、转弯角度等),并通过Matlab平台进行算法验证与仿真分析,展示多机协同的可行性与有效性。; 适合人群:具备一定Matlab编程基础,从事无人机控制、路径规划、智能优化算法研究的科研人员及研究生。; 使用场景及目标:①应用于灾害救援、军事侦察、区域巡检等多无人机协同任务场景;②目标是掌握多无人机系统在动态环境下的路径规划与防撞机制,提升协同作业能力与自主决策水平;③通过Matlab仿真深入理解协同算法的实现逻辑与参数调优方法。; 阅读建议:建议结合文中提供的Matlab代码进行实践操作,重点关注目标函数设计、避障策略实现与多机协同逻辑,配合仿真结果分析算法性能,进一步可尝试引入新型智能算法进行优化改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值