相同字符之间的最小距离

Minimum distance between same characters

本文关键字:距离 之间 字符      更新时间:2023-10-16

我想找出两个相同字符之间的最小距离(它们之间的字符数(。(如果存在多个,则返回最小的一个(

例如

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)

哈希是我能想到的一种方法。

假设:

  1. 输入中只有 26 个可能的字符 [a-z]。
  2. 如果没有两个相同的字符,则返回 INF。

基本思路:

我们只需要记住找到当前字符的最后一个索引,这将是对应于该位置的字符的最小距离(假设该字符不再出现(。我们可以使用变量来存储全局最小值。

方法:

  1. 创建一个大小为 26 的数组,以存储找到该字符的每个字符的最后一个索引。我们称数组为lastIndex[],

    • lastIndex[0]:存储找到字符"a"的最后一个索引。
    • lastIndex[1]:存储找到字符"b"的最后一个索引。
    • lastIndex[25]:存储找到字符"c"的最后一个索引。
  2. lastIndex的元素初始化为 -1。

  3. 初始化变量最小距离到 INF。
  4. 遍历所有元素。让位置表示对应于lastIndex中当前字符的索引。如果 lastIndex[position] 不等于 -1,则计算currentMinDistance = (idx - lastIndex[position] - 1(。如果当前最小距离小于最小距离,则将最小距离分配给当前最小距离lastIndex[position]更新为idx
  5. 返回最小距离

您可以扩展此方法,以便在更新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(,假设唯一字符的数量有限。