Skip to content

Update s0014_longest_common_prefix.rs #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

pro100skm
Copy link

Solution with one loop

Copy link

@shivaraaman shivaraaman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Old code only finds the longest common prefix and doesn't support . or *, so it fails on regex cases. New code uses 2D DP with nested loops to handle full pattern matching, passes all test cases, and runs efficiently in O(m × n) time for strings of length m and n. This code Suggests Solution using 2D Dynamic Programming with nested loops to handle . and * patterns for full string match.

// submission codes start here

impl Solution {
pub fn is_match(s: String, p: String) -> bool {
let s = s.as_bytes(); // Convert strings to byte arrays for fast indexing
let p = p.as_bytes();
let m = s.len();
let n = p.len();
let mut dp = vec![vec![false; n + 1]; m + 1];
dp[0][0] = true; // Empty pattern matches empty string
for j in 2..=n {
if p[j - 1] == b'' {
dp[0][j] = dp[0][j - 2];
}
}
for i in 1..=m {
for j in 1..=n {
if p[j - 1] == b'.' || p[j - 1] == s[i - 1] {
dp[i][j] = dp[i - 1][j - 1];
} else if p[j - 1] == b'
' {
dp[i][j] = dp[i][j - 2];
if p[j - 2] == b'.' || p[j - 2] == s[i - 1] {
dp[i][j] |= dp[i - 1][j];
}
}
}
}
dp[m][n]
}
}

// submission codes end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants