美文网首页
Duplicate Encoder

Duplicate Encoder

作者: Magicach | 来源:发表于2017-12-26 16:20 被阅读0次

    The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

    Examples:

    "din" => "((("

    "recede" => "()()()"

    "Success" => ")())())"

    "(( @" => "))(("

    Notes:

    There is a flaw in the JS version, that may occur in the random tests. Do not hesitate to do several attempts before modifying your code if you fail there.

    Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is actually the expected result, not the input! (these languages are locked so that's not possible to correct it).
    Good Solution1:

    public class DuplicateEncoder {
      static String encode(String word){
        word = word.toLowerCase();
        String result = "";
        for (int i = 0; i < word.length(); ++i) {
          char c = word.charAt(i);
          result += word.lastIndexOf(c) == word.indexOf(c) ? "(" : ")";
        }
        return result;
      }
    }
    

    Good Solution2:

    import java.util.stream.Collectors;
    
    public class DuplicateEncoder {
      static String encode(String word){    
            return word.toLowerCase()
                       .chars()
                       .mapToObj(i -> String.valueOf((char)i))
                       .map(i -> word.toLowerCase().indexOf(i) == word.toLowerCase().lastIndexOf(i) ? "(" : ")")
                       .collect(Collectors.joining());
      }
    }
    

    相关文章

      网友评论

          本文标题:Duplicate Encoder

          本文链接:https://www.haomeiwen.com/subject/rtdjgxtx.html