Skip to content

Commit 6446a8c

Browse files
committed
add 43 modified 32
1 parent 6b41231 commit 6446a8c

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

32.longest-valid-parentheses.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,53 @@
55
*/
66

77
// @lc code=start
8+
use std::cmp;
9+
810
impl Solution {
911
pub fn longest_valid_parentheses(s: String) -> i32 {
12+
let mut chars: Vec<char> = s.chars().collect();
13+
14+
let left2right = Self::longest_valid_parentheses_one_direction(&chars);
1015

16+
let mut charsMirror = vec![];
17+
chars.reverse();
18+
for ch in chars {
19+
if ch == '(' {
20+
charsMirror.push(')');
21+
} else {
22+
charsMirror.push('(');
23+
}
24+
}
25+
26+
let right2left = Self::longest_valid_parentheses_one_direction(&charsMirror);
27+
28+
cmp::max(left2right, right2left)
29+
}
30+
31+
pub fn longest_valid_parentheses_one_direction(chars: &Vec<char>) -> i32 {
32+
let N = chars.len();
33+
if N <= 1 { return 0; }
34+
35+
let mut balance = 0;
36+
let mut ans = 0;
37+
let mut start: i32 = -1;
38+
39+
for i in 0..N {
40+
if chars[i] == '(' {
41+
balance += 1;
42+
} else {
43+
balance -= 1;
44+
}
45+
46+
if balance < 0 {
47+
start = i as i32;
48+
balance = 0;
49+
} else if balance == 0 {
50+
ans = cmp::max(ans, i as i32 - start);
51+
}
52+
}
53+
54+
ans
1155
}
1256
}
1357
// @lc code=end

43.multiply-strings.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* @lc app=leetcode id=43 lang=rust
3+
*
4+
* [43] Multiply Strings
5+
*/
6+
7+
// @lc code=start
8+
use std::char;
9+
10+
impl Solution {
11+
pub fn multiply(num1: String, num2: String) -> String {
12+
let num1chars: Vec<char> = num1.chars().collect();
13+
let num2chars: Vec<char> = num2.chars().collect();
14+
15+
let N1 = num1.len();
16+
let N2 = num2.len();
17+
18+
let mut ans: Vec<u32> = vec![0; N1 + N2];
19+
20+
for i in 0..N1 {
21+
for j in 0..N2 {
22+
let x1 = num1chars[i].to_digit(10).unwrap_or(0);
23+
let x2 = num2chars[j].to_digit(10).unwrap_or(0);
24+
Self::add_num(&mut ans, x1 * x2, N1 - i + N2 - j - 2);
25+
}
26+
}
27+
28+
let mut s = String::new();
29+
30+
for num in ans {
31+
s.push(char::from_digit(num, 10).unwrap_or('0'));
32+
}
33+
34+
let ans = s.trim_left_matches('0').to_string();
35+
if ans == "" { "0".to_string() } else { ans }
36+
}
37+
38+
pub fn add_num(ans: &mut Vec<u32>, mut num: u32, shift: usize) {
39+
let N = ans.len();
40+
let mut idx = N - shift - 1;
41+
let mut carry = 0;
42+
43+
while (idx >= 0 && num > 0) || carry > 0 {
44+
let sum = ans[idx] + num % 10 + carry;
45+
ans[idx] = sum % 10;
46+
carry = sum / 10;
47+
num /= 10;
48+
idx -= 1;
49+
}
50+
}
51+
}
52+
// @lc code=end
53+

0 commit comments

Comments
 (0)