练习题整理——后缀子串排序(string类与short函数的应用)

题目简述

题目描述:

对于一个字符串,将其后缀子串进行排序,例如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运行会提示段溢出,为了保证程序对大数的处理能力和内存精简性,用动态数组的方式替代直接开辟大空间是个好习惯。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值