how to delete duplicate character from a string - java

The problem asks me to write a method to delete the duplicate characters from the original string and return the new string.For example, the original string is abracadabra and the result should be abrcd.
I was thinking about using StringBuilder to delete the character, but something went wrong when I tried to run the code. can anyone help me fix it.
public static String eliminateDuplicates(String str){
String result = "";
StringBuilder strings = new StringBuilder(str);
for(int i = 0; i<str.length(); i++){
for(int j = 1; j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
strings.deleteCharAt(j);
}
}
}
result = strings.toString();
return result;
}

Try this.
public static String eliminateDuplicates(String str){
int[] uniq = str.codePoints().distinct().toArray();
return new String(uniq, 0, uniq.length);
}

Using #P.J's idea
public static String eliminateDuplicates(String str) {
HashSet<Character> hashSet = new HashSet();
//A hashSet is a collection that only adds unique elements.
char[] toCharArray = str.toCharArray();
for (char c : toCharArray) {
hashSet.add(c);
}
StringBuilder answer = new StringBuilder();
for (Character character : hashSet) {
answer.append(character);
}
return answer.toString();
}

Try this code, maybe your can optimize :
public static String eliminateDuplicates(String source) {
StringBuilder result = new StringBuilder();
for (int i = 0, sLength = source.length(); i < sLength; i++) {
char readyToAdd = source.charAt(i);
boolean add = true;
for (int j = 0; j < result.length(); j++) {
if (readyToAdd == result.charAt(j)) {
add = false;
break;
}
}
if (add) result.append(readyToAdd);
}
return result.toString();
}

The code in question is iterating over input string but using the index to delete characters from the string builder object.
Every time the string builder deletes the character it will reduce in size. So, your code will fail with IndexOutofBoundsException. Please add the entire stack trace of the exception in the question to confirm, if that's the case.
A better approach to deleting duplicates is to create another string by iterating over the input string and then copying only the unique characters to new string. The new string can then be returned as a result.
This will also have better time complexity of O(n*m)compared to current code which had time complexity of O(n*n)

Try this
public static String eliminateDuplicates(String str){
StringBuilder result = new StringBuilder();
BitSet bs=new BitSet(256);
char[] chars=str.toCharArray();
char getChar=0;
for(int i=0;i<chars.length;i++){
getChar=chars[i];
if(!bs.get(getChar)){
result.append(getChar);
bs.set(getChar);
}
}
return result.toString();
}

Related

Best way to concatenate Strings in java(Time efficiency)

I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.

Java find difference between characters in StringBuffer

I'm working on an Anagram program and I'm currently working on a method called diff which should return a StringBuffer containing the chars that are in the first StringBuffer but not in the second one. So for example if the StringBuffers are abba and acca, then my diff method should return bb. So far I currently have loop with an if statement but it's not working. Any help would be appreciated. Thanks
public StringBuffer diff(){
StringBuffer diffVal = null;
for (int i =0; i < sBuffer1.length(); i++){
String let1 = String.valueOf(sBuffer1);
if (sBuffer2.indexOf(let1) == -1 ){
}
}
return diffVal;
I think you are trying to use a loop to examine one character by one character in sBuffer1. But String let1 = String.valueOf(sBuffer1); gives you the entire string of sBuffer1.
What you need is String let1 = sBuffer1.substring(i, i + 1) to take a single character from sBuffer1 to check if it exists in sBuffer2.
For example:
public static StringBuffer diff(StringBuffer sBuffer1, StringBuffer sBuffer2) {
StringBuffer diffVal = new StringBuffer();
for (int i = 0; i < sBuffer1.length(); i++) {
String let1 = sBuffer1.substring(i, i + 1); // get the character from sBuffer1
if (sBuffer2.indexOf(let1) == -1) {
diffVal.append(let1); // append the character to the diff
}
}
return diffVal;
}
ok this might work, your logic was a little bit wrong, this code is straight forward. search for the character if it doesn't exist in the second string buffer add it to the result SF.
public StringBuffer diff(){
StringBuffer diffVal = new StringBuffer();//initialize before you use it.
for (int i =0; i < sBuffer1.length(); i++){
String let1 = String.valueOf(sBuffer1.charAt(i))//get the character at the ith position.
if (sBuffer2.indexOf(let1) == -1 ){
diffVal.append(let1);
}
}
return diffVal;
}
Try this.
StringBuilder diffVal= new StringBuilder();
StringBuffer sBuffer1 = new StringBuffer("abbad");//input 1
StringBuffer sBuffer2 = new StringBuffer("acca");//input 2, you can ignore if you have already passed/defined these
for (int i =0; i < sBuffer1.length(); i++){
if(i >= sBuffer2.length()){//handles difference in input string length
diffVal.append(sBuffer1.substring(i, sBuffer1.length()));
break;
}
if (sBuffer1.charAt(i) != sBuffer2.charAt(i)) {
diffVal.append(sBuffer1.charAt(i));
}
}
System.out.println(diffVal);// I am printing it here
the out put is : bbd
One recommendation here is use StringBuilder if you the strings you are using here are not required to be synchronized

How to remove duplicate letters with a loop ( either for or while ) loop

Language : Java
Key Notes: *Needs to loop through a String using either a For loop or While loop
*It removes the duplicate letter(s) of the String and returns the word without the dupilcates.
Eg: The string is HELLO - The method then loops through and removes any duplicates, in this case " L " and returns in the end HELO
i have this so far
private String removeAnyDuplicates(String userWord)
{
//Code goes here?
return "" ; // Need to return the new string
}
You can do that with regular expressions. e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(.)\\1*");
public static void main(String[] args) {
String input = "HELLO, AABBCC";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("$1")
); // prints "HELO, ABC"
}
I'm assuming that removing duplicates means that the result contains at most one occurrence of any character. (Some of the other answers assume that adjacent duplicates only need to be reduced to single occurrences.) The basic algorithm would be:
initialize the result to the empty string
loop through each character of the input and if the character is not already present in the result, append it to the result
return the result
A naive (and very inefficient) implementation would be:
private String removeAnyDuplicates(String userWord)
{
String result = "";
for (int i = 0; i < userWord.length(); ++i) {
char c = result.charAt(i);
if (result.indexOf(c) < 0) {
// negative index indicates not present
result += String.valueOf(c);
}
}
return result;
}
This has two major sources of inefficiency: it creates many intermediate String objects and it has to scan the entire result so far for each character of the input. These problems can be solved by using some other built-in Java classes—a StringBuilder to more efficiently accumulate the result and a Set implementation to efficiently record and test which characters have already been seen:
private String removeAnyDuplicates(String userWord)
{
int len = userWord.length();
StringBuilder result = new StringBuilder(len);
Set<Character> unique = new HashSet<Character>();
for (int i = 0; i < len; ++i) {
char c = result.charAt(i);
// try to add c to set of unique characters
if (unique.add(c)) {
// if it succeeds, this is the first time seeing c
result.append(c);
}
}
return result.toString();
}
private String removeAnyDuplicates(String userWord)
{
CharSequence inputStr = userWord;
int length = inputStr.length();
Set<Character> uniqueChars = new HashSet<Character>();
for(int i=0; i < length; ++i) {
uniqueChars.add(inputStr.charAt(i));
}
return uniqueChars.size() >= 3;
}
check out this answer
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates.
Like this:
private static String removeAnyDuplicates(String userWord)
{
char[] chars = userWord.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
return sb.toString();
}
Remember:
import java.util.LinkedHashSet;
import java.util.Set;
You can try this
public static void main(String args[]){
System.out.println(removeAnyDuplicates("HELLO"));
}
private static String removeAnyDuplicates(String userWord)
{
char[] arr=userWord.toCharArray();
List<String> list=new ArrayList<>();
for(int i=0;i<arr.length;i++){
if(!list.contains(String.valueOf(arr[i]))){
list.add(String.valueOf(arr[i]));
}
}
return list.toString().replaceAll("\\[|\\]|\\,","") ;
}
Try this one liner:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)\\1+", "$1");
}
This uses a regular expression to find repeated (2 or more) letters and replaces them with a single instance of the letter.
It is unclear if "repeated" means appearing immediately after or anywhere after. For anywhere, use this:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)(?=.*\\1)", "");
}

Java: how do icheck if a certain character is within a string, then print out the position it is in relative to the string?

What I am trying to do, is create a method, that has a string and a character as parameters, the method then takes the string and searches for the given character. If the string contains that character, it returns an array of integers of where the character showed up. Here is what I have so far:
public class Sheet {
public static void main(String[] args) {
String string = "bbnnbb";
String complete = null;
//*******
for(int i = 0; i < string.length(); i++){
complete = StringSearch(string,'n').toString();
}
//********
}
public static int[] StringSearch(String string, char lookfor) {
int[]num = new int[string.length()];
for(int i = 0; i < num.length; i++){
if(string.charAt(i)== lookfor){
num[i] = i;
}
}
return num;
}
}
The method works fine, and returns this:
0
0
2
3
0
0
What I am trying to do, is make those into 1 string so it would look like this "002300".
Is there any possible way of doing this? I have tried to do it in the starred area of the code, but I have had no success.
just do
StringBuffer strBuff = new StringBuffer();
for(int i = 0; i<str.length(); i++)
{
if(str.charAt(i) == reqChar)
{
strBuff.append(str.charAt(i));
}
else
{
strBuff.append('0');
}
}
return str.toString();
Just add the result to the existing string with the += operator
String complete = "";
for(...)
complete += StringSearch(string,'n').toString();
I would just use java's regex library, that way it's more flexible (eg if you want to look for more than just a single character). Plus it's highly optimized.
StringBuilder positions = "";
Pattern pattern = Pattern.compile(string);
Matcher matcher = pattern.matcher(lookfor);
while(matcher.find()){
positions.append(matcher.start());
}
return positions;
Updated with StringBuilder for better practices.
public static String StringSearch(String string, char lookfor) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < string.length; i++){
if(string.charAt(i) == lookfor)
sb.append(i);
else
sb.append("0");
}
return sb.toString();
}
Then you can just call it once, without a for loop. Not sure why you call it for every character in the string.
complete = StringSearch(string,'n');

Removing duplicates from a String in Java

I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef should become abcdef
and the String abcdabcd should become abcd
Here is what I have so far:
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
What is the best way to do this?
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
System.out.println(sb.toString());
Using Stream makes it easy.
noDuplicates = Arrays.asList(myString.split(""))
.stream()
.distinct()
.collect(Collectors.joining());
Here is some more documentation about Stream and all you can do with
it :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
The 'description' part is very instructive about the benefits of Streams.
Try this simple solution:
public String removeDuplicates(String input){
String result = "";
for (int i = 0; i < input.length(); i++) {
if(!result.contains(String.valueOf(input.charAt(i)))) {
result += String.valueOf(input.charAt(i));
}
}
return result;
}
I would use the help of LinkedHashSet. Removes dups (as we are using a Set, maintains the order as we are using linked list impl). This is kind of a dirty solution. there might be even a better way.
String s="aabbccdef";
Set<Character> set=new LinkedHashSet<Character>();
for(char c:s.toCharArray())
{
set.add(Character.valueOf(c));
}
Create a StringWriter. Run through the original string using charAt(i) in a for loop. Maintain a variable of char type keeping the last charAt value. If you iterate and the charAt value equals what is stored in that variable, don't add to the StringWriter. Finally, use the StringWriter.toString() method and get a string, and do what you need with it.
Here is an improvement to the answer by Dave.
It uses HashSet instead of the slightly more costly LinkedHashSet, and reuses the chars buffer for the result, eliminating the need for a StringBuilder.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> present = new HashSet<>();
int len = 0;
for (char c : chars)
if (present.add(c))
chars[len++] = c;
System.out.println(new String(chars, 0, len)); // abcdeftz
Java 8 has a new String.chars() method which returns a stream of characters in the String. You can use stream operations to filter out the duplicate characters like so:
String out = in.chars()
.mapToObj(c -> Character.valueOf((char) c)) // bit messy as chars() returns an IntStream, not a CharStream (which doesn't exist)
.distinct()
.map(Object::toString)
.collect(Collectors.joining(""));
String input = "AAAB";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
but you cant use it if the input has the same elements, or if its empty!
Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:
import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}
public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+[]{}|;:',.<>/?`~";
for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}
return arr;
}
public static void main(String args[]){
String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;
result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;
char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");
}
}
How to read and talk about the above code:
The method called removeDupes takes an array of primitive char called arr.
arr is returned as an array of primitive characters "by value". The arr passed in is garbage collected at the end of Main's member method removeDupes.
The runtime complexity of this algorithm is O(n) or more specifically O(n+(small constant)) the constant being the unique characters in the entire array of primitive chars.
The copyOfRange does not increase runtime complexity significantly since it only copies a small constant number of items. The char array called arr is not stepped all the way through.
If you pass null into removeDupes, the method returns null.
If you pass an empty array of primitive chars or an array containing one value, that unmodified array is returned.
Method removeDupes goes about as fast as physically possible, fully utilizing the L1 and L2 cache, so Branch redirects are kept to a minimum.
A 2015 standard issue unburdened computer should be able to complete this method with an primitive char array containing 500 million characters between 15 and 25 seconds.
Explain how this code works:
The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.
We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.
when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.
At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.
Talking points exercise for coder interviews:
Will the program behave differently if you change the y++ to ++y? Why or why not.
Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.
Can you replace the double equals comparing primitive characters with a .equals? Why or why not?
Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?
Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?
public class RemoveRepeated4rmString {
public static void main(String[] args) {
String s = "harikrishna";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
Boolean found = false;
for (int j = 0; j < s2.length(); j++) {
if (s.charAt(i) == s2.charAt(j)) {
found = true;
break; //don't need to iterate further
}
}
if (found == false) {
s2 = s2.concat(String.valueOf(s.charAt(i)));
}
}
System.out.println(s2);
}
}
public static void main(String a[]){
String name="Madan";
System.out.println(name);
StringBuilder sb=new StringBuilder(name);
for(int i=0;i<name.length();i++){
for(int j=i+1;j<name.length();j++){
if(name.charAt(i)==name.charAt(j)){
sb.deleteCharAt(j);
}
}
}
System.out.println("After deletion :"+sb+"");
}
import java.util.Scanner;
public class dublicate {
public static void main(String... a) {
System.out.print("Enter the String");
Scanner Sc = new Scanner(System.in);
String st=Sc.nextLine();
StringBuilder sb=new StringBuilder();
boolean [] bc=new boolean[256];
for(int i=0;i<st.length();i++)
{
int index=st.charAt(i);
if(bc[index]==false)
{
sb.append(st.charAt(i));
bc[index]=true;
}
}
System.out.print(sb.toString());
}
}
To me it looks like everyone is trying way too hard to accomplish this task. All we are concerned about is that it copies 1 copy of each letter if it repeats. Then because we are only concerned if those characters repeat one after the other the nested loops become arbitrary as you can just simply compare position n to position n + 1. Then because this only copies things down when they're different, to solve for the last character you can either append white space to the end of the original string, or just get it to copy the last character of the string to your result.
String removeDuplicate(String s){
String result = "";
for (int i = 0; i < s.length(); i++){
if (i + 1 < s.length() && s.charAt(i) != s.charAt(i+1)){
result = result + s.charAt(i);
}
if (i + 1 == s.length()){
result = result + s.charAt(i);
}
}
return result;
}
String str1[] ="Hi helloo helloo oooo this".split(" ");
Set<String> charSet = new LinkedHashSet<String>();
for (String c: str1)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (String character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());
I think working this way would be more easy,,,
Just pass a string to this function and the job is done :) .
private static void removeduplicate(String name)
{ char[] arr = name.toCharArray();
StringBuffer modified =new StringBuffer();
for(char a:arr)
{
if(!modified.contains(Character.toString(a)))
{
modified=modified.append(Character.toString(a)) ;
}
}
System.out.println(modified);
}
public class RemoveDuplicatesFromStingsMethod1UsingLoops {
public static void main(String[] args) {
String input = new String("aaabbbcccddd");
String output = "";
for (int i = 0; i < input.length(); i++) {
if (!output.contains(String.valueOf(input.charAt(i)))) {
output += String.valueOf(input.charAt(i));
}
}
System.out.println(output);
}
}
output: abcd
You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?
You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.
Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)
Oldschool way (as we wrote such a tasks in Apple ][ Basic, adapted to Java):
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++){
for (j=i+1;j<str.length();j++){
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed non-unique symbols: " + str);
Here is another logic I'd like to share. You start comparing from midway of the string length and go backward.
Test with:
input = "azxxzy";
output = "ay";
String removeMidway(String input){
cnt = cnt+1;
StringBuilder str = new StringBuilder(input);
int midlen = str.length()/2;
for(int i=midlen-1;i>0;i--){
for(int j=midlen;j<str.length()-1;j++){
if(str.charAt(i)==str.charAt(j)){
str.delete(i, j+1);
midlen = str.length()/2;
System.out.println("i="+i+",j="+j+ ",len="+ str.length() + ",midlen=" + midlen+ ", after deleted = " + str);
}
}
}
return str.toString();
}
Another possible solution, in case a string is an ASCII string, is to maintain an array of 256 boolean elements to denote ASCII character appearance in a string. If a character appeared for the first time, we keep it and append to the result. Otherwise just skip it.
public String removeDuplicates(String input) {
boolean[] chars = new boolean[256];
StringBuilder resultStringBuilder = new StringBuilder();
for (Character c : input.toCharArray()) {
if (!chars[c]) {
resultStringBuilder.append(c);
chars[c] = true;
}
}
return resultStringBuilder.toString();
}
This approach will also work with Unicode string. You just need to increase chars size.
Solution using JDK7:
public static String removeDuplicateChars(final String str){
if (str == null || str.isEmpty()){
return str;
}
final char[] chArray = str.toCharArray();
final Set<Character> set = new LinkedHashSet<>();
for (char c : chArray) {
set.add(c);
}
final StringBuilder sb = new StringBuilder();
for (Character character : set) {
sb.append(character);
}
return sb.toString();
}
String str = "eamparuthik#gmail.com";
char[] c = str.toCharArray();
String op = "";
for(int i=0; i<=c.length-1; i++){
if(!op.contains(c[i] + ""))
op = op + c[i];
}
System.out.println(op);
public static String removeDuplicateChar(String str){
char charArray[] = str.toCharArray();
StringBuilder stringBuilder= new StringBuilder();
for(int i=0;i<charArray.length;i++){
int index = stringBuilder.toString().indexOf(charArray[i]);
if(index <= -1){
stringBuilder.append(charArray[i]);
}
}
return stringBuilder.toString();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveDuplicacy
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any word : ");
String s = br.readLine();
int l = s.length();
char ch;
String ans=" ";
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
}
System.out.println("Word after removing duplicate characters : " + ans);
}
}
public static void main(String[] args) {
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++)
{
for (j=1;j<str.length();j++)
{
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed String: " + str);
}
This is improvement on solution suggested by #Dave. Here, I am implementing in single loop only.
Let's reuse the return of set.add(T item) method and add it simultaneously in StringBuffer if add is successfull
This is just O(n). No need to make a loop again.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
if(charSet.add(c) ){
sb.append(c);
}
}
System.out.println(sb.toString()); // abcdeftz
Simple solution is to iterate through the given string and put each unique character into another string(in this case, a variable result ) if this string doesn't contain that particular character.Finally return result string as output.
Below is working and tested code snippet for removing duplicate characters from the given string which has O(n) time complexity .
private static String removeDuplicate(String s) {
String result="";
for (int i=0 ;i<s.length();i++) {
char ch = s.charAt(i);
if (!result.contains(""+ch)) {
result+=""+ch;
}
}
return result;
}
If the input is madam then output will be mad.
If the input is anagram then output will be angrm
Hope this helps.
Thanks
For the simplicity of the code- I have taken hardcore input, one can take input by using Scanner class also
public class KillDuplicateCharInString {
public static void main(String args[]) {
String str= "aaaabccdde ";
char arr[]= str.toCharArray();
int n = arr.length;
String finalStr="";
for(int i=0;i<n;i++) {
if(i==n-1){
finalStr+=arr[i];
break;
}
if(arr[i]==arr[i+1]) {
continue;
}
else {
finalStr+=arr[i];
}
}
System.out.println(finalStr);
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
String str = "";
char c;
for(int i = 0; i < s.length(); i++)
{
c = s.charAt(i);
str = str + c;
s = s.replace(c, ' ');
if(i == s.length() - 1)
{
System.out.println(str.replaceAll("\\s", ""));
}
}
}
package com.st.removeduplicate;
public class RemoveDuplicate {
public static void main(String[] args) {
String str1="shushil",str2="";
for(int i=0; i<=str1.length()-1;i++) {
int count=0;
for(int j=0;j<=i;j++) {
if(str1.charAt(i)==str1.charAt(j))
count++;
if(count >1)
break;
}
if(count==1)
str2=str2+str1.charAt(i);
}
System.out.println(str2);
}
}

Categories