Thursday, June 16, 2016

Three hackerrank challlenges

Applying for senior developer role.

First challenge is very easy:

Find first repeat word in a sentence. white space characters are ;,:,-,.,space and tab.
I failed one test case and guess it is because I used \s for space and tab. but it includes more characters.
The reason I used \\s is because I could not make it work with space and \\t the obvious right specification.

Later I realised the seemingly right regular expression failed due to forgot to escape the range letter hyphen (-) in []. It is expecting a valid range inside [] if you do not escape it. And unluckily I defined those characters after hypen :(


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package string;

import java.util.HashSet;
import java.util.Set;

public class FirstRepeatedWord {
 static String getFirstRepeatedWord(String s) {
  if (s == null)
   return null;
  if (s.length() == 0)
   return "";
  String[] words = s.split("[\\.;,:\\- \\t]+");
  // String[] words = s.split("[\\.[;,:-] \\t]+");
  Set<String> aSet = new HashSet<String>();
  for (String w : words) {
   if (!aSet.add(w))
    return w;
  }
  return "";
 }

 public static void main(String[] args) {
  System.out
    .println(getFirstRepeatedWord("abc   def,. cde-again\ttab\ttab"));

 }

}
Second one is to find most repeated substrings and report its repeating times. parameters need to parse from STDIN and result should be printed to STDOUT. it mentioned the string is all lower case and unique number of characters are no more than 26 characters. I did not have a good use of this information. Parameter includes length of string, range of substring's length, and number of allowed unique characters, as well as the string it self. I thought about a solution, but forget to use N to read all part of string from STDIN. I just read one line. The solution is to have two loop to parse out all valid substrings: length between k and l, with repeated characters no greater than m. everytime finding a substring, put it to hashmap for statistics. finally find most repeated substring and print its repeat time. Third one is to find all unique palindromes in a given string and report how many there are. I got this correct. solution: 1. figure out all palindromes by marking their index range. 2. adding them to set, and report size of set

No comments: