-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0336-PalindromePairs.cs
67 lines (56 loc) · 2.2 KB
/
0336-PalindromePairs.cs
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//-----------------------------------------------------------------------------
// Runtime: 620ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _0336_PalindromePairs
{
public IList<IList<int>> PalindromePairs(string[] words)
{
if (words == null || words.Length < 2) return new List<IList<int>>();
var result = new HashSet<IList<int>>();
var map = new Dictionary<string, int>();
for (int i = 0; i < words.Length; i++) map.Add(words[i], i);
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i])) continue;
for (int j = 0; j <= words[i].Length; j++)
{
var prefix = words[i].Substring(0, j);
var surfix = words[i].Substring(j);
if (IsPalindrome(prefix))
{
var surfixReverse = ReverseString(surfix);
if (map.ContainsKey(surfixReverse) && map[surfixReverse] != i)
result.Add(new List<int>() { map[surfixReverse], i });
}
if (IsPalindrome(surfix))
{
var prefixReverse = ReverseString(prefix);
if (map.ContainsKey(prefixReverse) && map[prefixReverse] != i && !string.IsNullOrEmpty(surfix))
result.Add(new List<int>() { i, map[prefixReverse] });
}
}
}
return new List<IList<int>>(result);
}
private string ReverseString(string str)
{
var sb = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
sb.Append(str[i]);
return sb.ToString();
}
private bool IsPalindrome(string str)
{
int left = 0, right = str.Length - 1;
while (left <= right)
if (str[left++] != str[right--]) return false;
return true;
}
}
}