The given string contains only three characters: "R" "G" "B". Sort the string. The final result is that R is placed after B in the previous G.
Requirement: the space complexity is O (1), and only one string can be traversed.
Http://write.blog.csdn.net/postedit in July Daniel's blog section 8 has the answer to this question.
When I was doing the question, I felt that if I had to sort two characters, it would be a trip in the fast sorting, and the two pointers would have been done. However, I also thought that three pointers would have to be used, but I don't know how to move it. I suddenly realized it was easy to read July's blog. The specific ideas are as follows:
The first begin, the first current in, and the second end are exchanged.
1. Current traversal. The entire array sequence. Current indicates 1 does not move,
2. Current refers to R, which is exchanged with begin, and then current ++, begin ++,
3. "current" refers to "B", which is switched with "end". Then, "current" does not move, and "end" is used --.
The three pointers control the positions of three RGB colors respectively, starting to point begin current to the first and end to the last
While (current <= end)
{
If (array [current] = 'R ')
{
Swap (array [current], array [begin]);
Current ++;
Begin ++;
}
Else if (array [current] = 'G ')
{
Current ++;
}
Else // when array [current] = 'B'
{
Swap (array [current], array [end]);
End --;
}
}
We also see how to deal with expansion, such as four-color, four-character