对字符串数组排序,使所有变位词都相邻(C++)

1,124 阅读3分钟

题目

编写一个函数,对字符串数组进行排序,将所有变位词排在相邻的位置。

思路1:利用sort函数

首先要清楚什么是变位词。变位词就是组成的字母相同,但顺序不一样的单词。 比如:live和evil就是一对变位词。

在C++中,排序可以通过STL中的sort函数快速实现。sort可以将字符串数组中的字符串按字典序排序。虽然本题中的要求是按照变位词的准则来排序,我们还是可以调用sort函数,不过要自己实现sort函数中的compare函数。

实现如下。

#include <iostream>
#include <algorithm>

using namespace std;

bool cmp(string s1, string s2){
    sort(s1.begin(), s1.end());   // 精髓所在
    sort(s2.begin(),s2.end());
    return s1 < s2;
}
int main(){
    string s[] = {
        "axyz", "abc", "yzax", "bac", "zyxa", "fg", "gf"
    };
    sort(s, s+7, cmp);
    for(int i=0; i<7; ++i)
        cout<<s[i]<<endl;
    return 0;
}

注释:

① sort函数

函数形式:C++ sort(first_pointer, first_pointer+n, cmp)

参数解释: 第一个参数是数组的首地址,一般写上数组名就可以,因为数组名是一个指针常量。第二个参数相对较好理解,即首地址加上数组的长度n(代表尾地址的下一地址)。最后一个参数是比较函数的名称(自定义函数cmp),这个比较函数可以不写,即第三个参数可以缺省,这样sort会默认按数组升序排序

函数拓展:cmp比较函数

//情况一:数组排列
int A[100];
bool cmp1(int a, int b)//int为数组数据类型
{
    return a > b;//降序排列
    //return a < b;//默认的升序排列
}
sort(A, A+100, cmp1);

//情况二:结构体排序
Student Stu[100];
bool cmp2(Student a, Student b)
{
    return a.id > b.id;//按照学号降序排列
    //return a.id < b.id;//按照学号升序排列
}
sort(Stu, Stu+100, cmp2);

② 注意事项

第一次看到本题,我的直接思路是利用sort函数实现降序,不定义cmp函数,运行结果并不符合要求。这是因为,对string数组利用sort函数直接进行降序排序,是“将字符串数组中的字符串按字典序排序”,string数组中单个string字符串本身并未得到排序,因此无法正确找到“变位词”。

// 直接利用sort函数排序,运行结果有误!!
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

bool cmp(string s1, string s2){
	//sort(s1.begin(), s1.end());
	//sort(s2.begin(), s2.end());
	return s1 < s2;
}
int main(){
	string s[] = {
		"axyz", "abc", "yzax", "bac", "zyxa", "fg", "gf"
	};
	sort(s, s + 7, cmp);
	for (int i = 0; i<7; ++i)
		cout << s[i] << endl;

	return 0;
}

运行结果:
// 可以看出以上string字符串均按照字典序排序
abc
axyz
bac
fg
gf
yzax
zyxa

思路2:哈希表排序




参考文献

[1] 写一个函数对字符串数组排序,使所有变位词都相邻

[2] leetcode 相同字母组成的不同单词归为一类即所谓的变位词

[3] 变位词排序

[4] 变位词排序