给定一个字符串,例如:
"all perfect"
我的目标是按字符统计单词的分数:a=1, b=2, c=3
ETC。
但如果我发现单词中有两个相同的连续字母( ll
代表 all
),则分数将乘以 2。
现在我已经编写了这段代码来计算线性词:
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
sum += 1 + ch - 'A';
System.out.printf("The sum of %s is %d%n", str, sum);
如果输入给出了单词的值,我如何计算它的值?我以前曾经分割过字符串。
String[] arr = str.split(" ");
int sumDupicate = consecutiveLetters(arr);
当我尝试执行该方法时,我遇到了一些问题:
public static int consecutiveLetters(String[] arr) {
for (int i = 0; i < arr.length; i++) {
int j;
int sum = 0;
char ch1, ch2;
for (j = 1; j < arr[i].length(); j++) {
ch1 = arr[i].charAt(j);
ch2 = arr[i].charAt(j - 1);
if (ch1 == ch2) {
//obviously this sum, count is wrong
sum += ((int) arr[i] -96)*2;
}
编辑:
如果我有这样一句话:
aabbcc
算法需要给出的分数:96 因为:
aabbcc =
double 12 * 2 = 24,
double it again = 24 *2 = 48
double it again = 48 * 2 = 96
每包含一个相邻的字母对,单词的分数就会加倍。 我希望现在我的要求已经明确。
最佳答案
public static int consecutiveLetters(String[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
char ch1, ch2;
double numberOfDuplicates = 0, word = 0;
for (int j = 0; j < arr[i].length()-1; j++) {
ch1 = arr[i].charAt(j);
ch2 = arr[i].charAt(j + 1);
if (ch1 == ch2) {
numberOfDuplicates++;
}
if(Character.isUpperCase(arr[i].charAt(j))) {
word += (int) arr[i].charAt(j) - 64;
} else {
word += (int) arr[i].charAt(j) - 96;
}
}
word += ((int) arr[i].charAt(arr[i].length()-1) - 96);
if(numberOfDuplicates > 0) {
double num = Math.pow(2, numberOfDuplicates);
word = word * num;
}
sum += word;
}
return sum;
}
Input: ["all"]
Output: 25
Input: ["aabbcc"]
Output: 96
关于Java:如何计算String[]数组中具有两个相同连续字母的单词的分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816871/