Segregating ‘R’ ‘G’ ‘B’ in a string in Java
In this Java tutorial, we will learn how to segregate R G B in a string in Java. You will find easy to understand algorithm with an easy code snippet. Input and output are also provided.
Problem: Separate R G B in a string in Java
We are given with a string “s” consists of characters ‘R’, ‘G’ and ‘B’. We have to segregate the characters in such a way that all ‘R’ comes in left of string, all ‘B’ in middle and all ‘G’ in right.
This problem is also a part of the famous Dutch national flag algorithm. In this Java tutorial, we are going to solve this problem by using switch statement.
How to split a string into array of characters in Java?
To split a string into array of characters we use string.CharArray() function in Java.
Syntax:- char[] s = str.toCharArray();
Algorithm:-
- Take three variables low , mid , high.
- Initialize low=0,mid=0,high=n-1.
- pass a[mid] as variable in switch condition.
- Whenever ‘R’ comes to swap a[mid] and a[low] and increment low and mid.
- Whenever ‘B’ comes just increment mid.
- Whenever ‘G’ comes to swap a[mid] and a[high] and decrement high.
Code Snippet to segregate R G B in a string in Java
while(mid<=high)
{
switch(s[mid])
{
case 'R' :
temp = s[low];
s[low] = s[mid];
s[mid] = temp;
low++; mid++;
break;
case 'B' :
mid++;
break;
case 'G' :
temp = s[mid];
s[mid] = s[high];
s[high] = temp;
high--;
break;
}
}
Java code to segregate ‘R’ ‘G’ and ‘B’ in a string
import java.util.Scanner;
import java.util.*;
class Codespeedy
{
public static void segregate(String str)
{
int n=str.length();
int low=0 , mid=0 , high=n-1;
char[] s = str.toCharArray();
char temp;
while(mid<=high)
{
switch(s[mid])
{
case 'R' :
temp = s[low];
s[low] = s[mid];
s[mid] = temp;
low++; mid++;
break;
case 'B' :
mid++;
break;
case 'G' :
temp = s[mid];
s[mid] = s[high];
s[high] = temp;
high--;
break;
}
}
System.out.print(s);
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
segregate(str);
}
}INPUT
RBRGRGBBRGBGR
OUTPUT
RRRRRBBBBGGGG
This type of problem also comes under the category of famous DutchFlagProblem.
Yoou may also learn,
Leave a Reply