-2

Design an autocomplete function for IDE. Given the String[] below, some capital letters and small letters are included in the input. We are asked to implement the autocomplete, and all capital letters must be matched. ex:

String[]  className {
        "GraphView",
        "DataGraphView",
        "DataController",
        "GraphViewController",
        "DataScienceView"
}

autocomplete(String[] className, "Data");  --> {"DataGraphView", "DataController", "DataScienceView"};
autocomplete(String[] className, "GVi");   -->  {"GraphView",  "GraphViewController"};
autocomplete(String[] className, "GraphController");   -->  {""};

I think maybe I could use trie, but I don't know how to handle the case2, which is "GVi". Does anyone who could help me on this? Any idea or codes are appreciated! Thanks a lot!

soufrk
  • 825
  • 1
  • 10
  • 24
  • 3
    Please show us that you put effort into solving your (homework?) assignment on your own. Post some code you came up with yourself over relying on us to solve it for you. – Ben Jul 02 '18 at 06:37
  • you are not asking any technical questions, basically, what you are looking for is someone to explain the business logic behind it all to you. Maybe you should ask that to the one who assigned you this task. – Stultuske Jul 02 '18 at 06:38

1 Answers1

0

That's actually not that difficult, I hope this will help you to think. Don't use too much StackOverflow for homework, or you'll have some trouble during tech interviews later in your life ;)

public static String[] autocomplete(String[] classNames, String input) {
    String inputAsRegexp = input.replaceAll("([A-Z][a-z]*)", "$1[a-z]*") + ".*";
    return Arrays.stream(classNames).filter(className -> className.matches(inputAsRegexp)).toArray(String[]::new);
}

First line prepare a regexp from the input. It detects an uppercase letter followed by any lowercase letters, then add an unlimited number of lowercase letters to go to the end of the name segment. Then it adds .* to matchs the remaining.

Example: GVi -> G[a-z]*Vi[a-z]*.*

Once I've made this regexp, I just filter the classnames based on it.

sjahan
  • 5,720
  • 3
  • 19
  • 42