Skip to content

Commit 5307da3

Browse files
committed
#3407: Substring Matching Pattern; solution & tests
1 parent 6997456 commit 5307da3

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* 3407
3+
* Substring Matching Pattern
4+
**
5+
* You are given a string s and a pattern string p,
6+
* where p contains exactly one '*' character.
7+
* The '*' in p can be replaced with any sequence of zero or more characters.
8+
*
9+
* Return true if p can be made a substring of s, and false otherwise.
10+
*
11+
* Example 1:
12+
* Input: s = "leetcode", p = "ee*e"
13+
* Output: true
14+
* Explanation:
15+
* By replacing the '*' with "tcod",
16+
* the substring "eetcode" matches the pattern.
17+
*
18+
* Example 2:
19+
* Input: s = "car", p = "c*v"
20+
* Output: false
21+
* Explanation:
22+
* There is no substring matching the pattern.
23+
*
24+
* Example 3:
25+
* Input: s = "luck", p = "u*"
26+
* Output: true
27+
* Explanation:
28+
* The substrings "u", "uc", and "uck" match the pattern.
29+
*
30+
* Constraints:
31+
* • 1 <= s.length <= 50
32+
* • 1 <= p.length <= 50
33+
* • s contains only lowercase English letters.
34+
* • p contains only lowercase English letters and exactly one '*'
35+
*
36+
* Hint 1:
37+
* Divide the pattern in two strings and search in the string.
38+
**
39+
* https://leetcode.com/problems/substring-matching-pattern/
40+
***/
41+
42+
using System;
43+
44+
namespace Problems;
45+
46+
public class SubstringMatchingPattern
47+
{
48+
public bool HasMatch( ReadOnlySpan<char> s, ReadOnlySpan<char> p )
49+
{
50+
int i = p.IndexOf( '*' );
51+
52+
ReadOnlySpan<char> p1 = p[..i];
53+
54+
int first = s.IndexOf( p1 );
55+
56+
if ( first == -1 )
57+
{
58+
return false;
59+
}
60+
61+
return s[( first + p1.Length )..]
62+
.IndexOf( p[( i + 1 )..] ) != -1;
63+
}
64+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class SubstringMatchingPatternTests
6+
{
7+
[TestCase( "leetcode", "ee*e", ExpectedResult = true )]
8+
[TestCase( "car", "c*v", ExpectedResult = false )]
9+
[TestCase( "luck", "u*", ExpectedResult = true )]
10+
public bool HasMatchTest( string s, string p ) =>
11+
new SubstringMatchingPattern().HasMatch( s, p );
12+
}

0 commit comments

Comments
 (0)