forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
50 lines (46 loc) · 1.56 KB
/
Solution.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
using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<IList<int>> PalindromePairs(string[] words) {
var results = new List<IList<int>>();
var reverseDict = words.Select((w, i) => new {Word = w, Index = i}).ToDictionary(w => new string(w.Word.Reverse().ToArray()), w => w.Index);
for (var i = 0; i < words.Length; ++i)
{
var word = words[i];
for (var j = 0; j <= word.Length; ++j)
{
if (j > 0 && IsPalindrome(word, 0, j - 1))
{
var suffix = word.Substring(j);
int pairIndex;
if (reverseDict.TryGetValue(suffix, out pairIndex) && i != pairIndex)
{
results.Add(new [] { pairIndex, i});
}
}
if (IsPalindrome(word, j, word.Length - 1))
{
var prefix = word.Substring(0, j);
int pairIndex;
if (reverseDict.TryGetValue(prefix, out pairIndex) && i != pairIndex)
{
results.Add(new [] { i, pairIndex});
}
}
}
}
return results;
}
private bool IsPalindrome(string word, int startIndex, int endIndex)
{
var i = startIndex;
var j = endIndex;
while (i < j)
{
if (word[i] != word[j]) return false;
++i;
--j;
}
return true;
}
}