0

Today when I was coding LeetCode 884. Uncommon Words from Two Sentences, I noticed that appending a char after a String is saving a little bit more time than appending a String after a String.

Here is my code: On line 2 and 3, I was using s1=s1+" ". After I changing it to s1=s1+' ', the run time was improved by 1s. I am wondering if appending char is more 'light-weighted'. If so, why? Thank you!

    public String[] uncommonFromSentences(String s1, String s2) {
        s1=s1+' ';
        s2=s2+' ';
       
        HashMap<String, Integer> map=new HashMap<>();
        ArrayList<String> al=new ArrayList<>();
        
        while (!s1.isEmpty()){
            int index= s1.indexOf(' ');
            
            String s=s1.substring(0, index);
            s1=s1.substring(index+1);
            
            map.put(s, map.getOrDefault(s,0)+1);
            
            
        }
        
        while (!s2.isEmpty()){
            int index=s2.indexOf(' ');
            
            String s=s2.substring(0, index);
            s2=s2.substring(index+1);
            
            map.put(s, map.getOrDefault(s,0)+1);
                       
        }
        
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            // System.out.println(entry.getValue() + " "+ entry.getKey());
            if(entry.getValue()==1){
               al.add(entry.getKey());
            }
        }
 
        return al.toArray(new String [al.size()]);
        
        
    }
}

Here is the link to the Leetcode Question: https://leetcode.com/problems/uncommon-words-from-two-sentences/

emily
  • 45
  • 1
  • 9
  • Just look at the source code for class `StringBuilder`. Compare method `append(char)` with method `append(String)` and the reason why `append(char)` is quicker will become obvious. Note that the string concatenation operator (`+`) actually calls methods of class `StringBuilder`. – Abra May 16 '21 at 14:37
  • I get it. Thank you Abra! – emily May 16 '21 at 14:38

0 Answers0