相同字符之间的最小距离
Minimum distance between same characters
我想找出两个相同字符之间的最小距离(它们之间的字符数(。(如果存在多个,则返回最小的一个(
例如
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 个可能的字符 [a-z]。
- 如果没有两个相同的字符,则返回 INF。
基本思路:
我们只需要记住找到当前字符的最后一个索引,这将是对应于该位置的字符的最小距离(假设该字符不再出现(。我们可以使用变量来存储全局最小值。
方法:
创建一个大小为 26 的数组,以存储找到该字符的每个字符的最后一个索引。我们称数组为lastIndex[],
- lastIndex[0]:存储找到字符"a"的最后一个索引。
- lastIndex[1]:存储找到字符"b"的最后一个索引。
- lastIndex[25]:存储找到字符"c"的最后一个索引。
- lastIndex[0]:存储找到字符"a"的最后一个索引。
将lastIndex的元素初始化为 -1。
- 初始化变量最小距离到 INF。
- 遍历所有元素。让位置表示对应于lastIndex中当前字符的索引。如果 lastIndex[position] 不等于 -1,则计算currentMinDistance = (idx - lastIndex[position] - 1(。如果当前最小距离小于最小距离,则将最小距离分配给当前最小距离。将lastIndex[position]更新为idx。
- 返回最小距离。
您可以扩展此方法,以便在更新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(,假设唯一字符的数量有限。
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 计算所有对之间的曼哈顿距离
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 两个有符号数字之间的距离
- 计算车辆之间的距离并设置速度,使距离保持不变,例如 5 米
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 查找彼此之间具有不同最小距离的随机数
- 相同字符之间的最小距离
- 如何排列二进制字符串以最小化它们之间的距离
- 堆和堆栈之间的距离
- 树节点之间的最大距离中的运行时错误
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 在 OpenCV 中计算 SURF 功能之间的距离
- 计算机如何分配两个变量,我们如何计算两个变量之间的距离?
- 是否有C 功能来计算两个索引之间的距离
- C++:快速/并行计算两个"std::vector<double>"向量之间的L1距离
- 2 点分配之间的 C++ 距离
- 使用指针计算三角形各点之间的距离