Skip to content

Commit 6826437

Browse files
committed
これだと普通に動かないかも。とりあえずコミット
1 parent a0ed98b commit 6826437

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

src/longuest_palindromic.rs

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,60 @@
11
pub struct Solution;
22
impl Solution {
3-
pub fn longest_palindrome(s: String) -> String {}
3+
pub fn longest_palindrome(s: String) -> String {
4+
// charのベクタに変換
5+
let s: Vec<char> = s.chars().collect();
6+
7+
// もし空文字なら空文字を返す
8+
if s.len() == 0 {
9+
return "".to_string();
10+
}
11+
12+
// もし一文字ならその文字を返す
13+
if s.len() == 1 {
14+
return s[0].to_string();
15+
}
16+
17+
// 回文で最長の長さを保持する変数
18+
struct Result {
19+
max_length: usize,
20+
string: String,
21+
}
22+
23+
let mut result = Result {
24+
max_length: 0,
25+
string: "".to_string(),
26+
};
27+
28+
// 両端のインデックスを定義
29+
let mut left = 0;
30+
let mut right = 0;
31+
32+
// シャクトリする外側ループ
33+
'outer: while right < s.len() {
34+
// 回文であるか検証する内側ループ
35+
let mut buffer = vec![];
36+
for i in left..=right {
37+
buffer.push(s[i]);
38+
}
39+
40+
if buffer == buffer.iter().rev().cloned().collect::<Vec<char>>() {
41+
// 回文であれば、次の文字を検証する
42+
// まず、
43+
if right - left + 1 > result.max_length {
44+
result = Result {
45+
max_length: right - left + 1,
46+
string: buffer.iter().collect(),
47+
};
48+
}
49+
right += 1;
50+
} else {
51+
// 回文でなければ、左端を次に進める
52+
left += 1;
53+
}
54+
}
55+
56+
return result.string;
57+
}
458
}
559

660
#[cfg(test)]

0 commit comments

Comments
 (0)