Using TreeSet - leetcode cannot find constructor for TreeSet. Am I on the right track for this question?


  • 0
    S
    public class Solution {
        public String removeDuplicateLetters(String s) {
            
            Set<Character> set = new HashSet<Character>();
            boolean added = false;
            
            for(int i = 0; i < s.length(); i++){
                Character c = s.charAt(i);
                added = set.add(c);
            }
            
            Set<Character> ts = new TreeSet<Character>(new myComp());
            ts.addAll(set);
            
            StringBuilder sb = new StringBuilder();
            for(Character c: ts){
               sb.append(c); 
            }
            
            String answer = sb.toString();
            
            return answer;
        }
       
    }
    
     class myComp implements Comparator<String>{
            @Override
            public int compare(String s1, String s2){
                return s1.compareTo(s2);
            }
        }

  • 1

    The problem is that the TreeSet<Character> constructor needs a comparator for characters, not for strings.


  • 0
    L

    @StefanPochmann, Just curious, how did you highlight the term TreeSet<Character>?


  • 0

    With backticks around it. You can also use ctrl-K or the code-button (if you see the editor menu, i.e., not if you write just a comment).


  • 0
    L

    Thank you so much! :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.