Is Beautiful String
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. Note that letter a
has no previous letter.
Given a string, check whether it is beautiful.
Example
For
inputString = "bbbaacdafe"
, the output should beis_beautiful_string(inputString) = true
This string contains 3
a
s, 3b
s, 1c
, 1d
, 1e
, and 1f
(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 beis_beautiful_string(inputString) = false
Since there are more
b
s thana
s, this string is not beautiful.For
inputString = "bbc"
, the output should beis_beautiful_string(inputString) = false
Although there are more
b
s thanc
s, this string is not beautiful because there are noa
s, so therefore there are moreb
s thana
s.
Input/Output
[input] string inputString
A string of lowercase English letters.
Solution
import string
def is_beautiful_string(input_string):
count_dict = sorted([
(k, input_string.count(k))
for k in set((input_string))
])
if(count_dict[0][0] != 'a'):
return False
for i in range(len(count_dict) - 1):
if(
ord(count_dict[i+1][0]) - ord(count_dict[i][0]) != 1
or
count_dict[i+1][1] > count_dict[i][1]
):
return False
return True
print(is_beautiful_string('bcdeff'))
print(is_beautiful_string('aabb'))
function isBeautifulString(inputString) {
const charMap = {};
const charCode = 'a'.charCodeAt(0);
for (let i = 0; i < 26; i++) {
charMap[String.fromCharCode(charCode + i)] = 0;
}
for (let i = 0; i < inputString.length; i++) {
charMap[inputString[i]]++;
}
const charMapKeys = Object.keys(charMap);
for (let i = 0; i < charMapKeys.length - 1; i++) {
if (charMap[charMapKeys[i]] < charMap[charMapKeys[i + 1]]) {
return false;
}
}
return true;
}
console.log(isBeautifulString('bcdeff'));
console.log(isBeautifulString('aabb'));
console.log(isBeautifulString('bbc'));