There are lots of questions which need to count occurence of English letters in a string. For the first thought, you may think of using map. However, we can take advantage of how language treat char, and we may be able to use array instead.
We see 'a' has value of 97 and 'A' has value of 65
Count occurences of letters in a string which consists of lowercase English letters.
//for Java
var counts = new int[26];
for(char c: s.toCharArray()) counts[c-97]++;
//lower letter string to [26]int
func convertToLetterArr(s string) [26]int {
var letters[26] int
for _, c := range []rune(s) {
letters[c-97]++
}
return letters
}
No comments:
Post a Comment