LeetCode336. Palindrome Pairs

Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1:

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]] 
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2:

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]] 
Explanation: The palindromes are ["battab","tabbat"]

参考资料:here

因为参考资料已经讲解得非常好了,我们这里就不在做说明了。不过需要注意得是,原解答没有用到set这个数据结构,所以他专门使用一个for循环来解决边界情况。

class Solution {
private:
	bool isPanlindrome(string s) {
		int left = 0, right = int(s.size() - 1);
		while (left < right) {
			if (s[left] != s[right]) return false;
			left++; right--;
		}
		return true;
	}
public:
	vector<vector<int>> palindromePairs(vector<string>& words) {
		map<string, int> m;
		for (int i = 0; i < words.size();i++) {
			string word = words[i];
			reverse(word.begin(), word.end());
			m[word] = i;
		}

		set<vector<int>> s;
		for (int i = 0; i < words.size(); i++) {
			string word = words[i];
			for (int j = 0; j <= word.size(); j++) {
				string left = word.substr(0, j);
				string right = word.substr(j);
				if (m.find(left) != m.end()) {
					if (isPanlindrome(right) && m[left] != i) {
						s.insert({i, m[left]});
					}
				}
				if (m.find(right) != m.end()) {
					if (isPanlindrome(left) && m[right] != i) {
						s.insert({ m[right], i });
					}
				}
			}
		}
		vector<vector<int>> ans(s.begin(), s.end());
		return ans;
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值