后缀子串排序(string类与sort函数的应用)
题目简述
题目描述:
对于一个字符串,将其后缀子串进行排序,例如grain
其子串有:
grain
rain
ain
in
n
然后对各子串按字典顺序排序,即:
ain,grain,in,n,rain
输入:
每个案例为一行字符串。
输出:
将子串排序输出
样例输入:
grain
样例输出:
ain
grain
in
n
rain
AC代码
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s;
int i, j, l;
while(cin>>s)
{
string *a,t;
l = s.length();
a =new string[l];
for (i = 0; i <l; i++)
{
a[i] = s.substr(i,l);
}
/*
for (i = l-1; i >= 0; i--)
for (j = i-1; j >=0 ; j--)
if (a[j]>a[i])
{
t=a[i];
a[i]= a[j];
a[j]=t;
}
*/
sort(a, a+l);
for (i = 0; i < l; i++)
cout << a[i] << endl;
delete[] a;
}
return 0;
}
string中substr函数的功能
std::string::substr
string substr (size_t pos = 0, size_t len = npos) const;
Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object.
The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
——引自http://www.cplusplus.com/reference/string/string/substr/
sort函数对字符数组排序的功能
本题起初采用了冒泡排序,可见在string下字符串数组的排序实现过程与数字数组排序十分相像。看前人代码,发现亦可直接用sort函数string数组进行排序,其排序方式即为按字典顺序。
< algorithm>
std::sort
default (1)
template < class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
——引自 http://www.cplusplus.com/reference/algorithm/sort/
动态数组的意义
在本题中,若直接开辟一个100*100的char数组的空间进行数据的存放,在OJ运行会提示段溢出,为了保证程序对大数的处理能力和内存精简性,用动态数组的方式替代直接开辟大空间是个好习惯。