RGB字符排序

来源:互联网 发布:js中set的用法 编辑:程序博客网 时间:2024/06/07 04:45
给定一个字符串里面只有"R" "G" "B" 三个字符,请排序,最终结果的顺序是R在前 G中 B在后。

要求:空间复杂度是O(1),且只能遍历一次字符串。

void fun(char a[], int n){int i = -1;while (a[i+1] == 'R'){i++;}int j = n;while (a[j-1] == 'B'){j--;}int p = i+1;while (p < j){if (a[p] == 'R'){i++;swap(a[p], a[i]);while (a[i+1] == 'R'){i++;}if (a[p] == 'B'){continue;}}else if (a[p] == 'B'){j--;swap(a[p], a[j]);while (a[j-1] == 'B'){j--;}if (a[p] == 'R'){continue;}}p++;}}


原创粉丝点击