Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
static String deleteCharsof2String(String fs,String ss){
int map[] = new int[256];
for (int i = 0; i < ss.length(); i++) {
map[ss.charAt(i)] =1;
}
char array[] = fs.toCharArray();
int k=0;
for (int i = 0; i < fs.length(); i++) {
if(map[fs.charAt(i)]!=1)
array[k++] = fs.charAt(i);
}
if(k != fs.length())
array[k] = '\n';
return new String(array);
}
#include<iostream>
#include<string>
using namespace std;
void printArray(char *input, int length)
{
for(int i = 0; i < length; i++)
cout<<input[i];
cout<<endl;
}
void deleteLetter(char *string1, char *string2, int length1, int length2)
{
bool isExisted[256];
for(int i = 0; i < 256; i++)
isExisted[i] = false;
for(int i = 0; i < length2; i++)
isExisted[string2[i]] = true;
int tail = 0;
for(int i = 0; i < length1; i++)
{
if(isExisted[string1[i]])
continue;
string1[tail] = string1[i];
tail++;
}
string1[tail] = '\0';
printArray(string1, tail);
}
int main()
{
char string1[] = "Hello";
char string2[] = "Hai";
deleteLetter(string1, string2, strlen(string1), strlen(string2));
}
public class Subtraction
{
public static void main(String arg[])
{
String first="Hello";
String second="Hai";
int len1=first.length();
int len2=second.length();
StringBuffer result =new StringBuffer();
int i=0,j=0;
while(i<len1)
{
boolean flag=false;
j=0;
while(j<len2)
{
if(first.charAt(i)==second.charAt(j))
flag=true;
j++;
}
if(!flag)
result.append(first.charAt(i));
i++;
}
System.out.println(result.toString());
}
}
You can try this way too...
public static String findAndDelete(String a, String b){
StringBuffer result = new StringBuffer(a);
char[] c = b.toCharArray();
for (int i = 0; i < c.length; i++){
if (a.indexOf(c[i]) >= 0){
result.deleteCharAt(a.indexOf(c[i]));
a = result.toString();
}
}
return result.toString();
}
Assuming ASCII text, use a boolean array (or bit vector) of length 128. Set the vector to 1 for the position corresponding to the ASCII code of each character in the second word. Go through the first word letter by letter, identifying whether the character is in the second string or not by examining the array, and create a string of characters that are not in the second word. This has time complexity O(length of word 1 + length of word 2).
- Anonymous October 18, 2011