c++ - 相同字符之间的最小距离
问题描述
我想找出两个相同字符之间的最小距离(它们之间的字符数)。(如果存在多个返回最小的一个)
例如
1) Input = patent
<br>
output=2 (as t and t are 2 char away)
<br>
2) Input = pattern
<br>
output=0 (t and t are next to each other)<br>
3)Input = ababdbbdhfdksl
<br>
output=0 as (b and b are consecutive)
解决方案
散列是我能想到的一种方法。
假设:
- 输入中只有 26 个可能的字符 [az]。
- 如果没有两个相同的字符,则返回 INF。
基本理念:
我们只需要记住找到当前字符的最后一个索引,这将是与该位置的字符对应的最小距离(假设该字符不再出现)。我们可以使用变量来存储全局最小值。
方法:
创建一个大小为 26 的数组来存储找到它的每个字符的最后一个索引。让我们调用数组lastIndex [],
- lastIndex [0]:存储找到字符“a”的最后一个索引。
- lastIndex [1]:存储找到字符“b”的最后一个索引。
- lastIndex [25]:存储找到字符“c”的最后一个索引。
- lastIndex [0]:存储找到字符“a”的最后一个索引。
将lastIndex的元素初始化为 -1。
- 将变量minDistance初始化为 INF。
- 遍历所有元素。让position表示与lastIndex中的当前字符相对应的索引。如果 lastIndex[position] 不等于 -1,则计算currentMinDistance = (idx - lastIndex[position] - 1)。如果currentMinDistance小于minDistance,则将minDistance分配给currentMinDistance。将lastIndex[position]更新为idx。
- 返回minDistance。
您可以在更新minDistance时扩展此方法以存储元素的索引。
这是该方法的代码:
int getMinimumDistanceBetweenSameCharcters(const string &s){
int lastIndex[26];
for( int idx = 0; idx < 26 ; ++idx ){
lastIndex[idx] = -1;
}
int minDistance = INT_MAX;
for( int idx = 0; idx < s.size() ; ++idx ){
int position = s[idx] - 97; // ASCII
if( lastIndex[position] != -1 && (idx - lastIndex[position] - 1) < minDistance ){
minDistance = idx - lastIndex[position] - 1;
}
lastIndex[position] = idx;
}
return minDistance;
}
时间复杂度 - O(n),其中 n 是字符串的大小。
空间复杂度 - O(1),假设唯一字符的数量有限。
推荐阅读
- r - 将正方形或三角形标记(不是圆形)添加到 R 绘图地图
- qt - 在 QML 中嵌套加载器
- java - 将 windows.h 句柄返回给 Java JNI
- python - Spyder IDE:修改服务器上的源代码
- python-3.x - 尝试更新 gensim 的 LdaModel 时出现 IndexError
- r - R - 在定义的阈值上选择矩阵列表中存在的相同行的省时方法
- c# - 将字符串解析为 datetimepicker 时出错
- google-people-api - 使用人员 API 创建联系人不支持 Internet 呼叫字段
- python - pandas .duplicated() 无法找到重复的行
- search - 可接纳性并不能保证 A* 的最优性?