-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathisBeautifulString.R
executable file
·63 lines (61 loc) · 1.89 KB
/
isBeautifulString.R
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# A string is said to be beautiful if each letter in the string appears at most
# as many times as the previous letter in the alphabet within the string; ie: b
# occurs no more times than a; c occurs no more times than b; etc.
#
# Given a string, check whether it is beautiful.
#
# Example
#
# For inputString = "bbbaacdafe", the output should be
# isBeautifulString(inputString) = true.
#
# This string contains 3 as, 3 bs, 1 c, 1 d, 1 e, and 1 f (and 0 of every other
# letter), so since there aren't any letters that appear more frequently than
# the previous letter, this string qualifies as beautiful.
#
# For inputString = "aabbb", the output should be isBeautifulString(inputString)
# = false.
#
# Since there are more bs than as, this string is not beautiful.
#
# For inputString = "bbc", the output should be isBeautifulString(inputString) =
# false.
#
# Although there are more bs than cs, this string is not beautiful because there
# are no as, so therefore there are more bs than as.
#
# Input/Output
#
# [execution time limit] 5 seconds (r)
#
# [input] string inputString
#
# A string of lowercase English letters.
#
# Guaranteed constraints: 3 ≤ inputString.length ≤ 50.
#
# [output] boolean
#
# Return true if the string is beautiful, false otherwise.
library(data.table)
# inputString = "bbbaacdafe"
isBeautifulString <- function(inputString) {
#get unique char and their occurence.
inputString <- strsplit(inputString,"")[[1]]
uniqueChar <- unique(inputString)
uniqueChar <- uniqueChar[order(uniqueChar)]
dtCharFreq <- data.table(
uniquechar = uniqueChar,
Freq = unlist(lapply(uniqueChar,function(x) {return(sum(inputString == x))}))
)
#add previous alphabets if missing
if (all(letters[seq(1:nrow(dtCharFreq))] %in% (dtCharFreq[,uniquechar]))) {
if (all(diff(dtCharFreq[,Freq]) <= 0)) {
return(TRUE)
} else {
return(FALSE)
}
} else {
return(FALSE)
}
}