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 :

No comments:

Post a Comment