和大神们学习每天一题(leetcode)-Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

本题并没有要求相关的回文字符串一定要放在一起,只需建立一个哈希表并对每个字符串排序后与哈希表里进行比较,就可以知道是否有变换字符串

功能测试用例:"triangle","integral","unclear","nuclear","romin"

特殊测试用例:"triangle","integral","unclear","nuclear","inetgral"

程序代码如下:

class Solution 
{
public:
	void FastSort(string &sNumber, int nBegin, int nEnd)//快速排序
	{
		if (nBegin >= nEnd)
			return;
		int nPos1 = nBegin;
		int sNMiddle = sNumber[nEnd], sNChange;
		for (int nPos2 = nBegin; nPos2 < nEnd; nPos2++)
		{
			if (sNumber[nPos2] < sNMiddle)
			{
				sNChange = sNumber[nPos1];
				sNumber[nPos1] = sNumber[nPos2];
				sNumber[nPos2] = sNChange;
				nPos1++;
			}
		}
		sNumber[nEnd] = sNumber[nPos1];
		sNumber[nPos1] = sNMiddle;
		FastSort(sNumber, nBegin, nPos1 - 1);
		FastSort(sNumber, nPos1 + 1, nEnd);
	}
	vector anagrams(vector &strs) 
	{
		vector vsResult;
		string sMiddle;
		map msnAnag;//建立一个哈希表
		for (int nTemp = 0; nTemp < strs.size(); nTemp++)
		{
			sMiddle = strs[nTemp];
			FastSort(sMiddle, 0, sMiddle.size() - 1);
			if (msnAnag.count(sMiddle)==0)//如果哈希表里不含有当前字符串则存入哈希表
			{
				msnAnag[sMiddle] = nTemp;
			}
			else//如果存在
			{
				if (msnAnag[sMiddle] >= 0)
				{
					vsResult.push_back(strs[msnAnag[sMiddle]]);//将哈希表内对应位置的字符串插入结果向量
					msnAnag[sMiddle] = -1;
				}
				vsResult.push_back(strs[nTemp]);//将当前字符串插入结果向量
			}
		}
		return vsResult;
	}
};


你可能感兴趣的:(Leetcode,leetcode,windows,编程,map)