File tree Expand file tree Collapse file tree 3 files changed +70
-1
lines changed Expand file tree Collapse file tree 3 files changed +70
-1
lines changed Original file line number Diff line number Diff line change
1
+ pub struct Solution { }
2
+ impl Solution {
3
+ pub fn rob ( nums : Vec < i32 > ) -> i32 {
4
+ if nums. len ( ) == 1 {
5
+ return nums[ 0 ] ;
6
+ } else if nums. len ( ) == 0 {
7
+ return 0 ;
8
+ }
9
+ std:: cmp:: max (
10
+ Self :: r ( & nums[ 1 ..nums. len ( ) ] ) ,
11
+ Self :: r ( & nums[ 0 ..nums. len ( ) - 1 ] ) ,
12
+ )
13
+ }
14
+
15
+ fn r ( nums : & [ i32 ] ) -> i32 {
16
+ let ( mut r1, mut r2) = ( 0 , 0 ) ;
17
+ for val in nums {
18
+ let temp = std:: cmp:: max ( r1 + val, r2) ;
19
+ r1 = r2;
20
+ r2 = temp;
21
+ }
22
+ std:: cmp:: max ( r1, r2)
23
+ }
24
+ }
Original file line number Diff line number Diff line change
1
+ use std:: ops:: RangeInclusive ;
2
+ pub struct Solution { }
3
+ impl Solution {
4
+ pub fn longest_palindrome ( s : String ) -> String {
5
+ let s = s. as_str ( ) ;
6
+ ( 0 ..s. len ( ) )
7
+ . fold ( "" , |current_longest, idx| {
8
+ current_longest
9
+ . longest ( s. longest_palindrome_around ( idx..=idx) )
10
+ . longest ( s. longest_palindrome_around ( idx..=idx + 1 ) )
11
+ } )
12
+ . into ( )
13
+ }
14
+ }
15
+
16
+ trait LongestPalindrome {
17
+ type Idx ;
18
+ fn longest_palindrome_around ( & self , center : RangeInclusive < Self :: Idx > ) -> & Self ;
19
+ fn longest < ' a > ( & ' a self , other : & ' a Self ) -> & ' a Self ;
20
+ }
21
+ impl LongestPalindrome for str {
22
+ type Idx = usize ;
23
+ fn longest_palindrome_around ( & self , center : RangeInclusive < Self :: Idx > ) -> & Self {
24
+ let ( mut start, mut end) = center. into_inner ( ) ;
25
+ let characters = self . as_bytes ( ) ;
26
+ loop {
27
+ if characters. get ( start) != characters. get ( end) {
28
+ return & self [ start + 1 ..end] ;
29
+ }
30
+ if let ( Some ( new_start) , Some ( new_end) ) = ( start. checked_sub ( 1 ) , end. checked_add ( 1 ) ) {
31
+ start = new_start;
32
+ end = new_end;
33
+ } else {
34
+ return & self [ start..=end] ;
35
+ }
36
+ }
37
+ }
38
+ fn longest < ' a > ( & ' a self , other : & ' a Self ) -> & ' a Self {
39
+ if self . len ( ) > other. len ( ) {
40
+ self
41
+ } else {
42
+ other
43
+ }
44
+ }
45
+ }
Original file line number Diff line number Diff line change 1
- mod house_robber ;
1
+ mod longest_palindromic ;
2
2
fn main ( ) { }
You can’t perform that action at this time.
0 commit comments