-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path214.shortest-palindrome.cs
More file actions
38 lines (33 loc) · 990 Bytes
/
214.shortest-palindrome.cs
File metadata and controls
38 lines (33 loc) · 990 Bytes
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
/*
* @lc app=leetcode id=214 lang=csharp
*
* [214] Shortest Palindrome
*/
// @lc code=start
public class Solution {
public string ShortestPalindrome(string s) {
// find largest palindrome substring starting from the beginning
for (var i = 0; i < s.Length; i++) {
if (isPalindrome(s.Substring(0, s.Length - i))) {
// append the substring which is a palindrome to the beginning of the string
return new string(s.Substring(s.Length - i).Reverse().ToArray()) + s;
}
}
// if the string is already a palindrome, return the string
return s;
}
public bool isPalindrome(string s) {
var i = 0;
var j = s.Length - 1;
// Loop from start to middle of the string
while (i < j) {
if (s[i] != s[j]) {
return false;
}
i++;
j--;
}
return true;
}
}
// @lc code=end