Thursday 8 August 2013

String Replacement


Replace all occurrence of the given pattern to ‘X’.

For example, given that the pattern=”abc”, replace “abcdeffdfegabcabc” with “XdeffdfegX”.

Note that multiple occurrences of abc’s that are contiguous will be replaced with only one ‘X’.

Solution:

class StringReplacementProblem{
static String replace(String str, String pattern){
if(str == null || str.length() == 0)
return str;

if(pattern == null || pattern.length() == 0)
return str;

return replaceHelper(str.toCharArray(), pattern);
}

static String replaceHelper(char []str, String pattern){
int runner = 0;
boolean flag = false;
 
              for(int i = 0; i < str.length; ){
//if pattern is found first time
if(flag == false && isMatch(str, pattern, i)){
str[runner++] = 'X';
i += pattern.length();
flag = true;
}
//if pattern is found more than one time continuously
else if(flag && isMatch(str, pattern, i)){
i+= pattern.length();
}else{//if pattern is not found
str[runner++] = str[i++];
flag = false;
}
}
return new String(str).substring(0, runner);
}

static boolean isMatch(char[] str, String pattern, int start){
for(int i = 0; i < pattern.length(); i++){
if(str[start] != pattern.charAt(i))
return false;
start++;
}
return true;
}

public static void main(String... args){
String str = "abcdefgabcabcabc";
String pattern = "abc";
System.out.println(replace(str, pattern));
}
 }

1 comment: