)RGB排序,一个字符串,里面只有三种字符R G B,所有的R都在G的前面,所有的G都在B的前面。将给定字符串按照此规律排序。要求不允许用辅助空间,复杂度控制在O(N)。遍历一遍就排好序。

来源:互联网 发布:流星搜剑录激活码淘宝 编辑:程序博客网 时间:2024/05/20 18:42
#include "stdafx.h"#include "stdlib.h"#include <string>#include <vector>#include <list>#include <algorithm>using namespace std;//算法中谈到了怎样不增加任何空间,交换两个元素的位置,在前面中介绍的是char型的加减法实现的,在做加减法实现的过程中要防止溢出,所以我这里换了个方法,使用异或实现!void swap(std::string &StrSrc,int i,int j)  {  StrSrc[i]=StrSrc[i]^StrSrc[j]; StrSrc[j]=StrSrc[j]^StrSrc[i]; StrSrc[i]=StrSrc[i]^StrSrc[j];  return;}  //返回flase表示排序已经完成bool StringSortGG(std::string &StrSrc,int &i,int &j){  int ibegin,iend; ibegin=i+1; iend=j-1; if (ibegin>iend) {  return false;  // } while (ibegin<=iend) {  //  if (StrSrc[ibegin]=='R')  {   swap(StrSrc,i,ibegin);   i++;   break;  }else if (StrSrc[iend]=='B')  {   swap(StrSrc,j,iend);   j--;   break;  }else if (StrSrc[ibegin]=='B')  {   swap(StrSrc,ibegin,j);   j--;   break;  }else if (StrSrc[iend]=='R')  {   swap(StrSrc,i,iend);   i++;  }else{   ibegin++;   iend--;      if (ibegin>iend)   {    return false;   }  } } return true;}bool StringSort(std::string &StrSrc){ // std::string StrSrc="RGBBGRRBRGRBBG"; if (StrSrc.empty()) {  return false; } int i=0; int j=StrSrc.length()-1; while (i<j) {    if (StrSrc[i]=='R')  {   i++;  }else if (StrSrc[j]=='B')  {   j--;  }else if (StrSrc[i]=='B')  {   swap(StrSrc,i,j);   j--;  }else if(StrSrc[j]=='R')  {   swap(StrSrc,i,j);   i++;  }else if ((StrSrc[i]=='G')&&(StrSrc[j]=='G'))  {   //   bool bRet=StringSortGG(StrSrc,i,j);   if (!bRet)   {    return true;   }     } }  return true;}int main(void){    std::string StrSrc="RGBBGRRBRGRBBG";    StringSort(StrSrc);}