-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
87 lines (69 loc) · 2.21 KB
/
Copy pathsolution.cpp
File metadata and controls
87 lines (69 loc) · 2.21 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Solution
{
public:
// Function to check whether a string is palindrome
bool isPalindrome(string &s, int left, int right)
{
// Compare characters from both ends
while (left < right)
{
// If mismatch found, not palindrome
if (s[left] != s[right])
{
return false;
}
left++;
right--;
}
return true;
}
bool palindromePair(vector<string> &arr)
{
// Store every string with its index
unordered_map<string, int> mp;
for (int i = 0; i < arr.size(); i++)
{
mp[arr[i]] = i;
}
// Traverse every word
for (int i = 0; i < arr.size(); i++)
{
string word = arr[i];
int n = word.length();
// Try every possible split
for (int j = 0; j <= n; j++)
{
// Left and right parts
string left = word.substr(0, j);
string right = word.substr(j);
// CASE 1:
// If left part is palindrome
if (isPalindrome(word, 0, j - 1))
{
// Reverse the right part
string revRight = right;
reverse(revRight.begin(), revRight.end());
// Check if reversed right exists
if (mp.count(revRight) && mp[revRight] != i)
{
return true;
}
}
// CASE 2:
// Avoid duplicate checking when right is empty
if (j != n && isPalindrome(word, j, n - 1))
{
// Reverse the left part
string revLeft = left;
reverse(revLeft.begin(), revLeft.end());
// Check if reversed left exists
if (mp.count(revLeft) && mp[revLeft] != i)
{
return true;
}
}
}
}
return false;
}
};