1. 程式人生 > >基於C++ STL sort函式對c++ string 進行字串的區域性排序

基於C++ STL sort函式對c++ string 進行字串的區域性排序


Paypal筆試掛了,因為好久沒有在leedcode之類的網上寫程式碼,字元輸入調了半天,時間都用光了。。。。

Description: 有一個字串,現在對其進行多次區域性排序,例如str="abcdef",輸入a=0, s=1,e=3,表示對abc這個子字串進行降序排列:cbadef。若a=1,表示按照升序排列,a=0表示降序;s,e表示起始和終止字元的位置。給出的輸入如下:

10 3
naitdocexv
1 1 3
0 9 10

1 7 9

10 代表字串的長度,3表示進行3次操作,下一行是字串,之後是三種操作,順序是a, s, e。

程式碼如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm> 
#include <fstream>

using namespace std;

int cmp0(char& a, char&  b)
{
	return a>b;
}
int cmp1(char& a, char& b)
{
	return a<b;
}

void ReorderOneTime(int a, int s, int e, char* str)
{
	if(a==0)
	{ 
		sort(str +s- 1, str+ e , cmp0);//不要用str+e-1,這裡sort中的第二個入參表示的字元不參與排序。
	}
	else
	{
		sort(str + s - 1, str+ e , cmp1);
	}
}
int main()
{
	ifstream cin("C:\\Users\\FrankFang\\Desktop\\234.txt");
	string str;
	int m, n;
	cin >> m;
	cin >> n;
	cin >> str;
	while (n>0)
	{
		int a, s, e;
		cin >> a; cin >> s; cin >> e;
		ReorderOneTime( a,  s,  e,  &str[0]);
		
		n--;
	}
	cout << str;
}