题目:一个字符串只有‘R’、‘G’、‘B’组成,如何让全部的‘R’出如今前面,全部的‘G’在中间,全部的‘B’在最后。ios
要求:要求空间复杂度为O(1),只许遍历一遍字符串数组数组
思路:维护三个游标 i、j、kide
i 指向开始, j 指向尾部,用于分别插入 R 、Bspa
k 用于遍历,当发现是R时,与前面的 i 指的对象交换,i 后移;
当发现是B时,与后面的 j指的对象交换,j前移对象
当 k与j相遇后中止字符串
- #include<iostream>
- using namespace std;
- void f(char * str)
- {
- int length=strlen(str);
- int i=0;
- int j=length-1;
- int k=0;
- while(k<=j)
- {
- // 当发现是R时,与前面的 i 指的对像交换,i后移 ;
- if(str[k]=='R')
- {
- char tmp=str[i];
- str[i]=str[k];
- str[k]=tmp;
- i++;
- }
- //当发现是B时,与后面的 j指的对像交换,j前移
- else if(str[k]=='B')
- {
- char tmp=str[j];
- str[j]=str[k];
- str[k]=tmp;
- j--;
- }
- else
- k++;
- }
- }
- void main()
- {
- char str[]="GRGBRBGBBRRGBRBG";
- cout<<str<<endl;
- f(str);
- cout<<str<<endl;
- }