给定一个字符串S及其长度N (假设N > 0 )。任务是找到相同的重复字符之间的最小距离,如果没有重复的字符出现在字符串S返回-1。
例子:
Input: S = “geeksforgeeks”, N = 13
Output: 0
Explanation:
The repeating characters in string S = “geeksforgeeks” with minimum distance is ‘e’.
The minimum difference of their indices is 0 (i.e. the character ‘e’ are present at index 1 and 2).
Input: S = “abdfhbih”, N = 8
Output: 2
Explanation:
The repeating characters in string S = “abdfhbih” with minimum distance is ‘h’.
The minimum difference of their indices is 2 (i.e. the character ‘h’ are present at index 4 and 7).
朴素的方法:这个问题可以使用两个嵌套循环来解决,一个循环考虑字符串S中每个索引‘i’处的一个元素,下一个循环将在S 中找到与第i个相同的匹配字符。
首先,将重复字符之间的每个差异存储在一个变量中,并检查此当前距离是否小于存储在同一变量中的先前值。最后返回存储最小值的变量。有一种极端情况,即当没有重复字符返回-1 。请按照以下步骤解决此问题:
- 将变量minDis初始化为N以存储重复字符的最小距离。
- 使用变量i在范围[0, N-1] 中迭代:
- 使用变量j在范围[i + 1, N-1] 中迭代:
- 如果S[i]等于S[j]并且它们之间的距离小于minDis,则更新minDis然后中断循环
- 使用变量j在范围[i + 1, N-1] 中迭代:
- 如果minDis值未更新,则表示没有重复字符,则返回-1,否则返回minDis – 1。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// This function is used to find
// minimum distance between same
// repeating characters
int shortestDistance(string S, int N)
{
// Store minimum distance between same
// repeating characters
int minDis = S.length();
// For loop to consider each element
// of string
for(int i = 0; i < N; i++)
{
for(int j = i + 1; j < N; j++)
{
// Comparison of string characters and
// updating the minDis value
if (S[i] == S[j] and (j - i) < minDis)
{
minDis = j - i;
// As this value would be least
// therefore break
break;
}
}
}
// If minDis value is not updated that means
// no repeating characters
if (minDis == S.length())
return -1;
else
// Minimum distance is minDis - 1
return minDis - 1;
}
// Driver Code
int main()
{
// Given Input
string S = "geeksforgeeks";
int N = 13;
// Function Call
cout << (shortestDistance(S, N));
}
// This code is contributed by lokeshpotta20
Java
// Java program for the above approach
import java.io.*;
class GFG{
// This function is used to find
// minimum distance between same
// repeating characters
static int shortestDistance(String S, int N)
{
// Store minimum distance between same
// repeating characters
int minDis = S.length();
// For loop to consider each element
// of string
for(int i = 0; i < N; i++)
{
for(int j = i + 1; j < N; j++)
{
// Comparison of string characters and
// updating the minDis value
if (S.charAt(i) == S.charAt(j) &&
(j - i) < minDis)
{
minDis = j - i;
// As this value would be least
// therefore break
break;
}
}
}
// If minDis value is not updated that means
// no repeating characters
if (minDis == S.length())
return -1;
// Minimum distance is minDis - 1
else
return minDis - 1;
}
// Driver code
public static void main(String[] args)
{
// Given input
String S = "geeksforgeeks";
int N = 13;
// Function call
System.out.println(shortestDistance(S, N));
}
}
// This code is contributed by MuskanKalra1
Python3
# Python3 implementation of above approach
# This function is used to find
# minimum distance between same
# repeating characters
def shortestDistance(S, N):
# Store minimum distance between same
# repeating characters
minDis = len(S)
# For loop to consider each element of string
for i in range(N):
for j in range(i+1, N):
# Comparison of string characters and
# updating the minDis value
if(S[i] == S[j] and (j-i) < minDis):
minDis = j-i
# As this value would be least therefore break
break
# If minDis value is not updated that means
# no repeating characters
if(minDis == len(S)):
return -1
else:
# Minimum distance is minDis - 1
return minDis - 1
# Driver Code
# Given Input
S = "geeksforgeeks"
N = 13
# Function Call
print(shortestDistance(S, N))
C#
// C# program for the above approach
using System;
class GFG{
// This function is used to find
// minimum distance between same
// repeating characters
static int shortestDistance(string S, int N)
{
// Store minimum distance between same
// repeating characters
int minDis = S.Length;
// For loop to consider each element
// of string
for(int i = 0; i < N; i++)
{
for(int j = i + 1; j < N; j++)
{
// Comparison of string characters and
// updating the minDis value
if (S[i] == S[j] && (j - i) < minDis)
{
minDis = j - i;
// As this value would be least
// therefore break
break;
}
}
}
// If minDis value is not updated that means
// no repeating characters
if (minDis == S.Length)
return -1;
// Minimum distance is minDis - 1
else
return minDis - 1;
}
// Driver code
public static void Main(String[] args)
{
// Given input
string S = "geeksforgeeks";
int N = 13;
// Function call
Console.Write(shortestDistance(S, N));
}
}
// This code is contributed by shivanisinghss2110
Javascript
Java
// Java implementation of above approach
import java.io.*;
import java.util.*;
class GFG{
// This function is used to find
// minimum distance between same
// repeating characters
static int shortestDistance(String S, int N)
{
// Define a hashmap and an arraylist
HashMap dic = new HashMap();
ArrayList dis = new ArrayList<>();
// Temporary variable
int var;
// Traverse through string
for(int i = 0; i < N; i++)
{
// If character present in dictionary
if (dic.get(S.charAt(i)) != null)
{
// Difference between current position
// and last stored value
var = i - dic.get(S.charAt(i));
// Updating current position
dic.put(S.charAt(i), i);
// Storing difference in list
dis.add(var);
}
// If character not in dictionary assign
// it with initial of its position
else
{
dic.put(S.charAt(i), i);
}
}
// If no element inserted in list
// i.e. no repeating characterss
if (dis.size() == 0)
return -1;
// Return minimum distance
else
return Collections.min(dis) - 1;
}
// Driver code
public static void main(String[] args)
{
// Given input
String S = "geeksforgeeks";
int N = 13;
// Function call
System.out.println(shortestDistance(S, N));
}
}
// This code is contributed by MuskanKalra1
Python3
# Python3 implementation of above approach
# This function is used to find the
# required the minimum distances of
# repeating characters
def shortestDistance(S, N):
# Define dictionary and list
dic = {}
dis = []
# Traverse through string
for i in range(N):
# If character present in dictionary
if S[i] in dic:
# Difference between current position
# and last stored value
var = i- dic[S[i]]
# Updating current position
dic[S[i]] = i
# Storing difference in list
dis.append(var)
# If character not in dictionary assign
# it with initial of its position
else:
dic[S[i]] = i
# If no element inserted in list
# i.e. no repeating characters
if(len(dis) == 0):
return -1
# Return minimum distance
else:
return min(dis)-1
# Driver code
# Given Input
S = "geeksforgeeks"
N = 13
# Function Call
print(shortestDistance(S, N))
C++
// C++ Program to find the minimum distance between two
// repeating characters in a string using two pointers technique
#include
using namespace std;
// This function is used to find
// minimum distance between any two
// repeating characters
// using two - pointers and hashing technique
int shortestDistance(string s, int n) {
// hash array to store character's last index
vector visited(128, -1);
int ans = INT_MAX;
// Traverse through the string
for(int right = 0; right < n; right++) {
char c = s[right];
int left = visited;
// If the character is present in visited array
// find if its forming minimum distance
if(left != -1)
ans = min(ans, right - left -1);
// update current character's last index
visited = right;
}
// Return minimum distance found, else -1
return ans == INT_MAX ? -1 : ans;
}
int main(){
// Given Input
string s = "geeksforgeeks";
int n = 13;
// Function Call
cout << (shortestDistance(s, n));
}
0
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:这个问题可以通过使用来解决 字典或散列。首先,存储针对字典字符的最后一个索引,以便可以与针对字典中相同字符存储的最后一个值相减,并进一步将距离存储在列表中。最后返回列表中的最小值。请按照以下步骤解决此问题:
- 初始化一个字典dic来保存最后一次出现的字符和一个列表dis来存储距离。
- 使用变量i在范围[0, N-1] 中迭代:
- 如果字典中存在字符:
- 然后,提取它的最后一个值dic[S[i]]并用当前位置i更新它。
- 将差值存储在变量var = i – dic[S[i]] 中并将其附加到列表dis。
- 如果该字符不存在,则使用当前位置进行初始化。
- 如果字典中存在字符:
- 如果dis的长度为0表示没有重复字符,则返回-1,否则返回min(dis) – 1。
下面是上述方法的实现:
Java
// Java implementation of above approach
import java.io.*;
import java.util.*;
class GFG{
// This function is used to find
// minimum distance between same
// repeating characters
static int shortestDistance(String S, int N)
{
// Define a hashmap and an arraylist
HashMap dic = new HashMap();
ArrayList dis = new ArrayList<>();
// Temporary variable
int var;
// Traverse through string
for(int i = 0; i < N; i++)
{
// If character present in dictionary
if (dic.get(S.charAt(i)) != null)
{
// Difference between current position
// and last stored value
var = i - dic.get(S.charAt(i));
// Updating current position
dic.put(S.charAt(i), i);
// Storing difference in list
dis.add(var);
}
// If character not in dictionary assign
// it with initial of its position
else
{
dic.put(S.charAt(i), i);
}
}
// If no element inserted in list
// i.e. no repeating characterss
if (dis.size() == 0)
return -1;
// Return minimum distance
else
return Collections.min(dis) - 1;
}
// Driver code
public static void main(String[] args)
{
// Given input
String S = "geeksforgeeks";
int N = 13;
// Function call
System.out.println(shortestDistance(S, N));
}
}
// This code is contributed by MuskanKalra1
蟒蛇3
# Python3 implementation of above approach
# This function is used to find the
# required the minimum distances of
# repeating characters
def shortestDistance(S, N):
# Define dictionary and list
dic = {}
dis = []
# Traverse through string
for i in range(N):
# If character present in dictionary
if S[i] in dic:
# Difference between current position
# and last stored value
var = i- dic[S[i]]
# Updating current position
dic[S[i]] = i
# Storing difference in list
dis.append(var)
# If character not in dictionary assign
# it with initial of its position
else:
dic[S[i]] = i
# If no element inserted in list
# i.e. no repeating characters
if(len(dis) == 0):
return -1
# Return minimum distance
else:
return min(dis)-1
# Driver code
# Given Input
S = "geeksforgeeks"
N = 13
# Function Call
print(shortestDistance(S, N))
0
时间复杂度: O(N)
辅助空间: O(N)
备用 解决方案:使用改进的两点方法也可以解决以下问题。这个想法基本上是为每个字符维护一个左指针,一旦重复该特定字符,左指针就会指向最近的字符索引。这样做时,我们可以维护一个变量 ans 来存储任意两个重复字符之间的最小距离。这可以使用访问向量数组来实现,该数组将在数组中存储当前字符的最近索引。
请按照以下步骤解决此问题:
- 初始化一个访问过的向量,用于存储任何字符的最后一个索引(左指针)
- 在 [0, N-1] 范围内迭代:
- 如果之前访问过该字符:
- 找出字符之间的距离并检查,如果两者之间的距离最小。
- 如果它小于之前的最小值,则更新其值。
- 更新当前字符在访问数组中的最后一个索引。
如果没有获得最小距离(即当 ans 的值为 INT_MAX 时),则表示没有重复字符。在这种情况下返回-1;
下面是上述方法的实现:
C++
// C++ Program to find the minimum distance between two
// repeating characters in a string using two pointers technique
#include
using namespace std;
// This function is used to find
// minimum distance between any two
// repeating characters
// using two - pointers and hashing technique
int shortestDistance(string s, int n) {
// hash array to store character's last index
vector visited(128, -1);
int ans = INT_MAX;
// Traverse through the string
for(int right = 0; right < n; right++) {
char c = s[right];
int left = visited;
// If the character is present in visited array
// find if its forming minimum distance
if(left != -1)
ans = min(ans, right - left -1);
// update current character's last index
visited = right;
}
// Return minimum distance found, else -1
return ans == INT_MAX ? -1 : ans;
}
int main(){
// Given Input
string s = "geeksforgeeks";
int n = 13;
// Function Call
cout << (shortestDistance(s, n));
}
0
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。