In: Computer Science
public static java.lang.String removerec(java.lang.String s)
Returns a string similar to the given string with all runs of consecutive, repeated characters removed. For example,
Parameters:
s - given string
Returns:
string created from s by removing runs of the same character
Code:
public class Main
{
public static String removerec(String s)
{
/*Create empty string*/
String res="";
int n=s.length();
for(int i=1;i<n;i++)
{
/*If a chacater not equals to it's previous character*/
if(s.charAt(i-1)!=s.charAt(i))
{
/*append previous character to cretaed string*/
res=res+s.charAt(i-1);
}
}
/*append last character of string*/
res=res+s.charAt(n-1);
return res;
}
public static void main(String[] args)
{
System.out.println(removerec("apple"));
System.out.println(removerec("banana"));
System.out.println(removerec("baaannannnnaa"));
}
}
Screenshots: