I have published an ebook. A compilation of 100 Java(Interview)Programming problems which have been solved . I have given clear explanation and the code in the book. Believe me when I say, this will kick start you to achieve the job at your dream company.

Click on this link to get you to the landing page. It is completely free when you use kindle amazon. Take a look at it.

It is Completely free if you have Kindle Unlimited plan. It is worth the read if you want to learn java on your mobile and if you can’t take a paperback to each and every place you travel to.

Remove Duplicates

Given a string remove duplicates characters and maintain the same order

Input Format: "Hello world hi" Output String: "Helo wrdhi"

Code:

public class Answer implements QuestionInterface

{

@Override

public String func(String str)

{

if(str==null)

return null;

else

{

StringBuffer s2=new StringBuffer(str);

for(int i=0;i<s2.length()-1;i++)

{

for(int j=i+1;j<s2.length();j++)

{

if(s2.charAt(i)==s2.charAt(j))

{

s2.deleteCharAt(j);

i--;

}

}

}

String ss;

ss=s2.toString();

if(ss==null)

return null;

else

return ss;

}

}

}

Explanation:

The problem is to find the duplicate characters that are present in given input string and to remove them without changing the order of the string.

To find the duplicate characters and to remove the duplicate character we use String buffer to delete the character at a particular position. Then the modified string buffer is converted to a string and returned to the user.

Algorithm:

If the input string is null the output is returned as null.

The string is converted to a string buffer that is mutable.

Now the characters of the input string is compared using the == condition and for loops.

When there is a similar character the character is deleted and the iterator i is decremented.

When there are no similar characters the iterators i and j are incremented until the string ends.

The string buffer is then converted to string using the toString() function and returned as output.

Author Architha Harinath

--

--

Code -> Understand-> Repeat is my motto. I am a Data Engineer who writes about everything related to Data Science and Interview Preparation for SDE.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store