Amazon Interview Question
Given a string, remove subsequent duplicate characters until we get a unique set of characters.
Ex: input ==> apple ; expected output ==> ale
Ex: input ==>appapple; expected output ==>le
The input will be in char array.
char[] removeDupes(Char[] inputString){
}
Interview Answers
public static String getNonRepeatingChar(String str){
String uniqueChar = "";
if(str.isEmpty() || str == null){
return uniqueChar;
}
for(char s : str.toCharArray()){
if(str.indexOf(s)==str.lastIndexOf(s)){
uniqueChar = uniqueChar+s ;
}
}
return uniqueChar;
}
public static void main(String arg[]){
System.out.println("Non Repeating String is "+getNonRepeatingChar("apple"));
}
}
/*Given a string, remove subsequent duplicate characters until we get a unique set of characters.
Ex: input ==> apple ; expected output ==> ale
Ex: input ==>appapple; expected output ==>le
*/
import java.util.ArrayList;
public class RemoveDuplicateCharacters {
public static void main(String[] args) {
// TODO Auto-generated method stub
String S = "appapple";
int sLen = S.length();
ArrayList alStr = new ArrayList();
ArrayList rejectStr = new ArrayList();
Boolean flag;
for(int i =0;i< sLen;i++)
{
flag = true;
for(int j=i+1;j< sLen; j++)
{
if(S.charAt(j)==S.charAt(i) || rejectStr.contains(S.charAt(i)))
{
flag = false;
rejectStr.add(S.charAt(i));
break;
} //If condition
} //for loop j
if(flag == true)
{
alStr.add(S.charAt(i));
} //If condition
} //For Loop i
System.out.println(alStr);
}
}
public String returnSimplifiedString() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string: ");
String s = scan.nextLine();
String retVal = "";
ArrayList temp = new ArrayList();
for(char ch: s.toCharArray())
temp.add(s.charAt(ch));
for(char ch: temp) {
if(Collections.frequency(temp, ch) == 1) {
retVal = retVal+ch;
}
}
return retVal;
}
char[] removeDupes(char[] inputString)
{
Set set = new LinkedHashSet();
for(char ch : inputString)
{
if(set.contains(ch))
{
set.remove(ch);
}
else
{
set.add(ch);
}
}
char[] newarr=new char[set.size()];
int index=0;
for(Character cr : set)
{
newarr[index++]=cr;
}
return newarr;
}