在给定的字符串中查找按照字典顺序排列的字符数量
算法分析
按照字典顺序排列的字符具有的特点:
对于按字母顺序排列的子字符串,其字符的顺序与出现在英文字母中的顺序相同。此外,这种子串中连续字符的ASCII值正好相差1。若要查找按字母顺序排列的子字符串总数,请遍历给定的字符串并比较两个相邻的字符,如果它们是按字母顺序排列的,请将结果递增,然后在字符串中查找与其前一个字符不按字母顺序排列的下一个字符。
- 如果 str[i]+1 == str[i+1], 则将将结果增加1,并将字符串迭代到下一个不按字母顺序排列的字符
- 否则继续
str.charAt(i) + 1 == str.charAt(i + 1)
算法设计
package com.bean.algorithm.stringdemo;
public class FindAlphabeticOrderinString {
static int findSubstringCount(String str) {
int result = 0;
int n = str.length();
// 遍历字符串
for (int i = 0; i < n - 1; i++) {
// 判断字符是否按照字典顺序排列
if (str.charAt(i) + 1 == str.charAt(i + 1)) {
result++;
// 继续查找
while (str.charAt(i) + 1 == str.charAt(i + 1)) {
i++;
}
}
}
// 返回结果
return result;
}
public static void main(String args[]) {
String str = "qwertyuiopasdfghjklzxcvbnm";
System.out.println(findSubstringCount(str));
}
}
程序运行结果
3