Description

Solutions

Julia


using DataStructures, Test


"""
出现多于1次的字符编码为右括号,只有1次的为左括号
"""
#> "出现多于1次的字符编码为右括号,只有1次的为左括号\n"
function duplicateencode(word::String)::String
    lower_word = lowercase(word)

    dict = counter(lower_word)
    encode(c::Char)::Char = dict[c] > 1 ? ')' : '('

    map(encode, lower_word)
end
#> duplicateencode (generic function with 1 method)

@test duplicateencode("Success") == ")())())"
#> Test Passed
#>   Expression: duplicateencode("Success") == ")())())"
#>    Evaluated: ")())())" == ")())())"

R

## Duplicate Encoder

library(tidyverse)


#' @title 重复字符编码器
#' @description 只出现一次的字符转换为'(';出现多次的字符转换为')'
duplicate_encode <- function(word) {
    # 字符串拆解为字符向量
    chars <- tolower(word) %>%
        str_split("") %>%
        unlist()

    # 统计频数
    frequency <- table(chars)

    chars %>%
        map_chr(function(ch) {
            ifelse(frequency[ch] == 1, "(", ")")
        }) %>%
        str_c(collapse = "")
}

duplicate_encode("Success")
#> [1] ")())())"
library(testthat)
test_that("Sample Tests", {
    expect_equal(duplicate_encode("din"), "(((")
    expect_equal(duplicate_encode("recede"), "()()()")
    expect_equal(duplicate_encode("Success"), ")())())", "should ignore case")
    expect_equal(duplicate_encode("CodeWarrior"), "()(((())())")
    expect_equal(duplicate_encode("(( @"), "))((")
})
#> Test passed 🥇

JavaScript

const counter = require("../src/JavaScript/toolkit/Vector").counter;

/**
 * 重复字符编码器
 * @param {String} word 
 */
function duplicateEncode(word) {
  const lowerWord = word.toLowerCase();
  const dict = counter(lowerWord);
  return lowerWord.split("").map(c => dict[c] === 1 ? "(" : ")").join("");
}

console.log(duplicateEncode("Success"));
#> )())())