Given an array of strings, remove duplicates according to these rules:

  1. Two strings are identical when words matches (case insensitive) and order doesn't matter, so "apple Orange" == "APPLe oRange" == "ORANGE apple".
  2. If multiple identical strings exist, prefer the one that occurs at the last location, so if input is ["apple Orange", "ORANGE apple", "APPLe oRange", "HI There", "THERE hI"], only "APPLe oRange" and "THERE hI" will be returned.
  3. The relative order of the original array cannot be changed, so we cannot have result as ["THERE hI", "APPLe oRange"].

For example, given input:

["apple Orange", "ORANGE apple", "APPLe oRange", "HI There", "THERE hI"]

Return

["APPLe oRange", "THERE hI"]

asked 09 Jan, 07:11

1337c0d3r's gravatar image

1337c0d3r ♦♦
506335139
accept rate: 0%


My solution:

  1. Create a HashSet for checking duplicates and ArrayList for record results.
  2. Traverse the String array from end to begin, in each iteration, we convert every string to lowercase and sort it.
  3. If the set doesn't have the sorted string we got from step 2, we add it to the HashSet and add the current string to the ArrayList.
  4. Reverse the ArrayList and convert it to the String array for return.

My code is in the following:

import java.util.*;
public class Solution{
public String[] removeDuplicates(String[] input){
    HashSet<String> set = new HashSet<String>();
    ArrayList<String> ret = new ArrayList<String>();
    for(int i = input.length - 1; i >= 0; i--){
        String currString = input[i].toLowerCase();
        char currStringArray[] = currString.toCharArray();
        Arrays.sort(currStringArray);
        String sortedString = Arrays.toString(currStringArray);
        if(!set.contains(sortedString)){
            ret.add(input[i]);
            set.add(sortedString);
        }
    }
    Collections.reverse(ret);
    return ret.toArray(new String[ret.size()]);
}
public static void main(String args[]){
    String[] input = {"apple Orange", "ORANGE apple", "APPLe oRange", "HI There", "THERE hI"};
    Solution s = new Solution();
    String[] result = s.removeDuplicates(input);
    for(String e : result){
        System.out.println(e);
    }
}
link

answered 10 Jan, 01:17

wonderli's gravatar image

wonderli
111
accept rate: 0%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • Indent code by 4 spaces.
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×14

Asked: 09 Jan, 07:11

Seen: 762 times

Last updated: 10 Jan, 01:17