Skip to content

Commit

Permalink
update: May20 find longest awesome substring [H]
Browse files Browse the repository at this point in the history
  • Loading branch information
aucker committed May 20, 2024
1 parent 681ec7f commit e49fe51
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
28 changes: 28 additions & 0 deletions daily/May20.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
int longestAwesome(string s) {
int n = s.size();
unordered_map<int, int> prefix = {{0, -1}};
int ans = 0;
int sequence = 0;
for (int i = 0; i < n; i++) {
int digit = s[i] - '0';
sequence ^= (1 << digit);
if (prefix.count(sequence)) {
ans = max(ans, i - prefix[sequence]);
} else {
prefix[sequence] = i;
}
for (int k = 0; k < 10; k++) {
if (prefix.count(sequence ^ (1 << k))) {
ans = max(ans, i - prefix[sequence ^ (1 << k)]);
}
}
}

return ans;
}
};
29 changes: 29 additions & 0 deletions daily/cpp/1542_find_longest_awesome_substring.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
int longestAwesome(string s) {
int n = s.size();
unordered_map<int, int> prefix = {{0, -1}};
int ans = 0;
int sequence = 0;
for (int i = 0; i < n; i++) {
int digit = s[i] - '0';
sequence ^= (1 << digit);
if (prefix.count(sequence)) {
ans = max(ans, i - prefix[sequence]);
} else {
prefix[sequence] = i;
}

for (int k = 0; k < 10; k++) {
if (prefix.count(sequence ^ (1 << k))) {
ans = max(ans, i - prefix[sequence ^ (1 << k)]);
}
}
}

return ans;
}
};
Empty file.
29 changes: 29 additions & 0 deletions daily/rust/1542_find_longest_awesome_substring.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use std::collections::HashMap;

impl Solution {
/// Time: O(n|\Sigma|), n: len(s), \Sigma: charset, 10 chars
/// Space: O(min{n, 2^{|\Sigma|}}), the space that hash mapping
pub fn longest_awesome(s: String) -> i32 {
let mut prefix: HashMap<i32, i32> = HashMap::new();
prefix.insert(0, -1);
let mut ans = 0;
let mut sequence = 0;
for (i, ch) in s.chars().enumerate() {
let digit = ch.to_digit(10).unwrap() as i32;
sequence ^= (1 << digit);
if let Some(&prev_index) = prefix.get(&sequence) {
ans = ans.max(i as i32 - prev_index);
} else {
prefix.insert(sequence, i as i32);
}

for k in 0..10 {
if let Some(&prev_index) = prefix.get(&(sequence ^ (1 << k))) {
ans = ans.max(i as i32 - prev_index);
}
}
}

ans
}
}

0 comments on commit e49fe51

Please sign in to comment.