-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0459_repeated_substring_pattern.rs
More file actions
39 lines (36 loc) · 1.1 KB
/
s0459_repeated_substring_pattern.rs
File metadata and controls
39 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#![allow(unused)]
pub struct Solution {}
// google interview
impl Solution {
pub fn repeated_substring_pattern(s: String) -> bool {
let n = s.len();
let mut dp = vec![0;n];
// Construct partial match table (lookup table).
// It stores the length of the proper prefix that is also a proper suffix.
// ex. ababa --> [0, 0, 1, 2, 1]
// ab --> the length of common prefix / suffix = 0
// aba --> the length of common prefix / suffix = 1
// abab --> the length of common prefix / suffix = 2
// ababa --> the length of common prefix / suffix = 1
let chs = s.chars().collect::<Vec<char>>();
for i in 1..n {
let mut j = dp[i -1];
while j > 0 && chs[i] != chs[j] {
j = dp[j - 1];
}
if chs[i] == chs[j] {
j += 1;
}
dp[i] = j;
}
let l = dp[n - 1];
// check if it's repeated pattern string
return l != 0 && n % (n - l) == 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1002() {}
}