Wednesday, June 15, 2016

stringClean - Recursive - Java & C#

Given a string, return recursively a "cleaned" string where adjacent chars that are the same have been reduced to a single char. So "yyzzza" yields "yza".

stringClean("yyzzza") → "yza"
stringClean("abbbcdd") → "abcd"
stringClean("Hello") → "Helo"

Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public String stringClean(String str) {
  //Stop Condition
  if(str.length()<2) return str;
  
  //Main recursive process
  int index = 0;
  for(index=0; index+1<str.length(); index++)
  {
    if(str.charAt(index) != str.charAt(index+1)) break;
  }
  return str.charAt(index)+stringClean(str.substring(index+1));
}

Test Result:

C#:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 public static string stringClean(string str)
        { 
            //kondisi setop
            if (str.Length < 2) return str;

            //main rekursif
            int index = 0;
            for (index=0; index+1 < str.Length; index++)
            {
                if (str[index] != str[index + 1]) break;
            }

            return str[index] + stringClean(str.Substring(index+1));

        }

Test Result :

allStar - Recursive - Java & C#

Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".

allStar("hello") → "h*e*l*l*o"
allStar("abc") → "a*b*c"
allStar("ab") → "a*b"
Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static String allStar(String str)
 {
  //Stop Condition
  if(str.length()<1) return "";
  if(str.length() == 1) return str+"*";
  
  
  //Main recursive process
  return str.charAt(0)+"*"+allStar(str.substring(1));
 }

Hasil :

C# :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
   public static string allStar(String str)
        { 
            //Kondisi stop
            if (str.Length < 1) return "";
            if (str.Length == 1) return str;


            //Proses rekursif
            return str[0] + "*" + allStar(str.Substring(1));
        }

Hasil :