Amazon Interview Question
Quality Assurance EngineersCountry: India
Interview Type: In-Person
If you cannot even use .length then I would do it inside a while loop and not a for loop. To improve the big O notation you can use recursing while dividing the array I guess. Not too sure about that.
couldn't find any other way of reading char from console..
public class StringReplacement {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
char c=scanner.next().charAt(0);
String str1= scanner.next();
String str2= scanner.next();
String newstr=new String();
for(char ch:str1.toCharArray()){
if(ch==c){
newstr=newstr+str2;
}
else{
newstr=newstr+ch;
}
}
System.out.println(newstr);
}
}
void find_and_replace(char **S1, const char ch, const char* S2)
{
char* str1 = strdup(*S1);
int m=0;
while(str1[m] != '\0')
{
if(str1[m] != ch)
{
m++;
}
else
{
str1 = realloc(str1, strlen(str1) + strlen(S2));
memcpy(str1 + m + strlen(S2), str1 + m + 1, strlen(str1 + m + 1));
strncpy(str1 + m, S2, strlen(S2));
m += strlen(S2);
}
}
*S1 = str1;
}
int main()
{
char* S1 = "this is a test";
char* S2 = "blah";
char ch = 't';
printf("%s\n", S1);
find_and_replace(&S1, ch, S2);
printf("%s\n", S1);
return 0;
}
Represent the Strings as char[], scan the first string once, to count the number of times that char c is present, now calculate the length of the final string, and fill it from backwards O(2n) = O(n)
Example: abcdcdef and xyz are 2 strings, represent them as a char[], given char c, now scan first string, we find c twice, so the final string length is 8 - 1 + 3 - 1 + 3 = 12, create a new char[] and fill it from backwards with the first string, but when u hit c, fill it with the second string xyz instead of the c.
public class ReplaceCharFromString{
public static void main(String []args){
String str1 = "stauvwamna";
char[] arr1 = str1.toCharArray();
char str2 = 'X';
char chr = 'a';
for(int i=0;i<arr1.length;i++){
if(arr1[i]==chr){
arr1[i]=str2;
System.out.println(arr1[i]);
}else
System.out.println(arr1[i]);
}
}
}
public static String insertString(String subject, String inserter, char c1) {
String result = subject;
char[] array = result.toCharArray();
for (int i = 0; i < array.length; i++ ) {
if (array[i] == c1) {
result = new StringBuilder(result).replace(i, i+1, inserter).toString();
i+= (inserter.length()-1);
array = result.toCharArray();
}
}
return result;
}
- Nuruddin January 22, 2014