一个字符数组,里面的字符可能是a-z、A-Z、0-9.现在要求对数组进行排序,要求所有小写字符放在最前面,所有大写字符放在中间,所有数字放在最后,而且各部分内部分别有序(创新工场)

一个字符数组,里面的字符可能是a-z、A-Z、0-9.现在要求对数组进行排序,要求所有小写字符放在最前面,所有大写字符放在中间,所有数字放在最后,而且各部分内部分别有序。思路:先进行字符串排序,用堆排序,按降序排列,排列依据字母对应的ascii值。排序之后按字符类别进行翻转。时间复杂度O(nlogn)

#include
#include
using namespace std;

void swap(char* a, char* b) {
	char temp = *a;
	*a= *b;
	*b = temp;
}

void heapAdjust(char* str, int i, int length) {
	int lchild = 2 * i + 1;
	int rchild = 2 * i + 2;
	int minIndex;
	if (lchild < length && str[lchild] < str[i])
		minIndex = lchild;
	else
		minIndex = i;
	if (rchild < length && str[rchild] < str[minIndex])
		minIndex = rchild;
	if (minIndex != i) {
		swap(str + i, str + minIndex);
		heapAdjust(str, minIndex, length);
	}
}

void heapSort(char* str, int length) {
	int i;
	for (i = length / 2; i >= 0; i--)
		heapAdjust(str, i, length);
	for (i = length - 1; i > 0; i--) {
		swap(str + i, str + 0);
		heapAdjust(str, 0, i);
	}
}

void revserStr(char* pStart, char* pEnd) {
	char charTemp;
	while (pStart < pEnd) {
		charTemp = *pStart;
		*pStart = *pEnd;
		*pEnd = charTemp;
		pStart++;
		pEnd--;
	}
}

void rearrangeStr(char* pStr, int length) {
	heapSort(pStr, length);
	int i, startIndex = 0, endIndex = -1;
	for (i = 0; i < length; i++) {
		if (pStr[i] >= 'a' && pStr[i] <= 'z') {
			endIndex++;
		} else {
			break;
		}
	}
	if (endIndex > startIndex)
		revserStr(pStr + startIndex, pStr + endIndex);
	startIndex = endIndex + 1;
	for (; i < length; i++) {
		if (pStr[i] >= 'A' && pStr[i] <= 'Z') {
			endIndex++;
		} else {
			break;
		}
	}
	if (endIndex > startIndex)
		revserStr(pStr + startIndex, pStr + endIndex);
	startIndex = endIndex + 1;
	for (; i < length; i++) {
		if (pStr[i] >= '0' && pStr[i] <= '9') {
			endIndex++;
		} else {
			break;
		}
	}
	if (endIndex > startIndex)
		revserStr(pStr + startIndex, pStr + endIndex);

}

int main(int argc, char* argv[]) {
	char str[] = "MDEXE098FGH453a4cf9";
	int length = strlen(str);
	rearrangeStr(str, length);
	cout << str << endl;
	cin.get();
	return 0;
}


你可能感兴趣的:(字符串问题)