给定一个仅由小写字母组成的大小为N的字符串S ,任务是找到在其连续重复之间具有最小距离总和的最小字符。如果字符串S仅由不同的字符组成,则打印“-1” 。
例子:
Input: str = “aabbaadc”
Output: b;
Explanation:
For all the characters in the given string, the sum of the required distances are as follows:
Indices of ‘a’ = {0, 1, 4, 5}
=> Sum of the distances of its next repetition = abs(0 – 1) + abs(4 – 1) + abs(5 – 4) = 5
Indices of ‘b’ = {2, 3}
=> Sum of the distances of its next repetition = abs(2 – 3) = 1
‘c’, ‘d’ has no repetition
From the above distances the minimum sum of distance obtained is 1, for the character ‘b’.
Therefore, the required answer is ‘b’.
Input: str = “abcdef”
Output: -1
Explanation:
All the characters in the given string are distinct.
朴素的方法:最简单的方法是遍历给定的字符串,对于每个字符,单独找到最短距离的总和。以最小的最短距离打印最小的字符。
时间复杂度: O(N*26),其中 N 是给定字符串的长度。
辅助空间: O(N)
高效的方法:思想是遍历字符串一次,找到每个字符的第一个和最后一个索引,因为相同字符之间索引之间的差值之和就是第一个和最后一个字符之间的差值。请按照以下步骤解决问题:
- 创建长度等于26的数组last[]和first[]将两个数组初始化为-1 。
- 用一些大数初始化min 。
- 遍历字符串S并将当前字符的第一次出现更新为当前索引,如果它等于-1 。
- 查找每个字符最后出现的位置并将其存储在数组last[] 中。
- 如果两个索引都具有非负值,则遍历数组并更新在每个对应处具有最小差异的索引。
- 如果在索引x处找到最小索引,则打印字符(x + ‘a’) 。
- 否则,打印“-1” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the character
// repeats with minimum distance
char minDistChar(string s)
{
int n = s.length();
// Stores the first and last index
int* first = new int[26];
int* last = new int[26];
// Initialize with -1
for (int i = 0; i < 26; i++) {
first[i] = -1;
last[i] = -1;
}
// Get the values of last and
// first occurence
for (int i = 0; i < n; i++) {
// Update the first index
if (first[s[i] - 'a'] == -1) {
first[s[i] - 'a'] = i;
}
// Update the last index
last[s[i] - 'a'] = i;
}
// Initialize min
int min = INT_MAX;
char ans = '1';
// Get the minimum
for (int i = 0; i < 26; i++) {
// Values must not be same
if (last[i] == first[i])
continue;
// Update the minimum distance
if (min > last[i] - first[i]) {
min = last[i] - first[i];
ans = i + 'a';
}
}
// return ans
return ans;
}
// Driver Code
int main()
{
string str = "geeksforgeeks";
// Function Call
cout << minDistChar(str);
return 0;
}
Java
// Java program for
// the above approach
import java.util.*;
class GFG{
// Function to find the character
// repeats with minimum distance
static char minDistChar(char []s)
{
int n = s.length;
// Stores the first and last index
int []first = new int[26];
int []last = new int[26];
// Initialize with -1
for (int i = 0; i < 26; i++)
{
first[i] = -1;
last[i] = -1;
}
// Get the values of last and
// first occurence
for (int i = 0; i < n; i++)
{
// Update the first index
if (first[s[i] - 'a'] == -1)
{
first[s[i] - 'a'] = i;
}
// Update the last index
last[s[i] - 'a'] = i;
}
// Initialize min
int min = Integer.MAX_VALUE;
char ans = '1';
// Get the minimum
for (int i = 0; i < 26; i++)
{
// Values must not be same
if (last[i] == first[i])
continue;
// Update the minimum distance
if (min > last[i] - first[i])
{
min = last[i] - first[i];
ans = (char) (i + 'a');
}
}
// return ans
return ans;
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
// Function Call
System.out.print(minDistChar(str.toCharArray()));
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach
import sys
# Function to find the character
# repeats with minimum distance
def minDistChar(s):
n = len(s)
# Stores the first and last index
first = []
last = []
# Intialize with -1
for i in range(26):
first.append(-1)
last.append(-1)
# Get the values of last and
# first occurence
for i in range(n):
# Update the first index
if (first[ord(s[i]) - ord('a')] == -1):
first[ord(s[i]) - ord('a')] = i
# Update the last index
last[ord(s[i]) - ord('a')] = i
# Intialize the min
min = sys.maxsize
ans = '1'
# Get the minimum
for i in range(26):
# Values must not be same
if (last[i] == first[i]):
continue
# Update the minimum distance
if (min > last[i] - first[i]):
min = last[i] - first[i]
ans = i + ord('a')
return chr(ans)
# Driver Code
if __name__ == "__main__":
str = "geeksforgeeks"
# Function call
print(minDistChar(str))
# This code is contributed by dadi madhav
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the character
// repeats with minimum distance
static char minDistChar(char []s)
{
int n = s.Length;
// Stores the first and last index
int []first = new int[26];
int []last = new int[26];
// Initialize with -1
for(int i = 0; i < 26; i++)
{
first[i] = -1;
last[i] = -1;
}
// Get the values of last and
// first occurence
for(int i = 0; i < n; i++)
{
// Update the first index
if (first[s[i] - 'a'] == -1)
{
first[s[i] - 'a'] = i;
}
// Update the last index
last[s[i] - 'a'] = i;
}
// Initialize min
int min = int.MaxValue;
char ans = '1';
// Get the minimum
for(int i = 0; i < 26; i++)
{
// Values must not be same
if (last[i] == first[i])
continue;
// Update the minimum distance
if (min > last[i] - first[i])
{
min = last[i] - first[i];
ans = (char)(i + 'a');
}
}
// return ans
return ans;
}
// Driver Code
public static void Main(string[] args)
{
String str = "geeksforgeeks";
// Function call
Console.Write(minDistChar(str.ToCharArray()));
}
}
// This code is contributed by rutvik_56
Javascript
g
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。