-5
\$\begingroup\$

Solution:

public class RemoveDuplicateInString {

    public void removeDuplicate(String s){
        System.out.println("Before::"+s);
        int len = s.length();
        for(int i=0;i<len-1;i++){
            char c = s.charAt(i);
            String preString = s.substring(0,i+1);
            String temp = s.substring(i+1);
            temp = temp.replaceAll(""+c, "");
            System.out.println("....::"+temp);
            s =  preString + temp;
            len = s.length();
        }
        System.out.println("After::"+s);
    }

    public static void main(String args[]){
         RemoveDuplicateInString duplicate  = new RemoveDuplicateInString();
         duplicate.removeDuplicate("adfahagabfgdbah");
    }

}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why not use an array? Can you give us some context for this problem? \$\endgroup\$ Commented May 29, 2016 at 6:46
  • \$\begingroup\$ Simple reason is not to use array or collection and do it only with string. Because doing it with array or collection would be bit easy. \$\endgroup\$ Commented May 29, 2016 at 13:34
  • \$\begingroup\$ Sometimes it's not about ease it's about memory and CPU usage. Of course speed as well. \$\endgroup\$ Commented May 29, 2016 at 23:58

1 Answer 1

2
\$\begingroup\$

This code is highly ineffective, as it uses lot of string concatenation, and temporary strings, that's for StringBuilder is designed for.

public class RemoveDuplicateInString {

    public String removeDuplicate(String s){
        StringBuilder sb = new StringBuilder(s.length());
        int len = s.length();

        for(int i=0;i<len;i++){
            char c = s.charAt(i);
            if(sb.indexOf(String.valueOf(c))==-1)
                sb.append(c);
        }

        return sb.toString();
    }

    public static void main(String args[]){
        RemoveDuplicateInString duplicate  = new RemoveDuplicateInString();
        String s = "adfahagabfgdbah";

        System.out.println("Before::"+s);
        String s2 = duplicate.removeDuplicate(s);
        System.out.println("After::"+ s2);
    }
}

This will have O(n* log(n)) complexity, or O(n*m), where m is count of unique characters.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.