Posts Remove Duplicates (geeksforgeeks - SDE Sheet)
Post
Cancel

Remove Duplicates (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a string str without spaces, the task is to remove all duplicate characters from it, keeping only the first occurrence.

Note: The original order of characters must be kept the same.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {

    String removeDups(String str) {

        int[] chars = new int[26];

        StringBuffer sb = new StringBuffer();

        for(int i=0; i<str.length(); i++){

            char ch = str.charAt(i);

            if(chars[ch - 'a'] == 0){
                sb.append(ch + "");
                chars[ch - 'a'] = 1;
            }

        }

        return sb.toString();

    }

}
This post is licensed under CC BY 4.0 by the author.