📌  相关文章
📜  字符串中的最小字符,其连续重复之间的距离之和最小

📅  最后修改于: 2021-05-17 21:52:46             🧑  作者: Mango

给定大小为N的字符串S (仅由小写字母组成),任务是找到最小字符,其连续重复之间的距离之和最小。如果字符串S仅由不同的字符组成,则打印“ -1”

例子:

天真的方法:最简单的方法是遍历给定的字符串,对于每个字符,分别找到最短距离的总和。以最小的最短距离打印最小的字符。

时间复杂度: O(N * 26),其中N是给定字符串的长度。
辅助空间: O(N)

高效的方法:想法是遍历字符串一次并找到每个字符的第一个和最后一个索引,因为相同字符之间的索引之间的差之和就是第一个和最后一个字符之间的差。请按照以下步骤解决问题:

  1. 创建长度等于26的数组last []first [] ,将两个数组都初始化为-1
  2. 用一些大数字初始化min
  3. 遍历字符串S并将当前字符的第一个匹配项更新为当前索引(如果它等于-1)
  4. 查找每个字符的最后一次出现并将其存储在数组last []中
  5. 如果两个索引都具有非负值,则遍历数组并更新在每个对应的索引处具有最小差异的索引。
  6. 如果在索引x处找到最小索引,则打印字符(x +’a’)
  7. 否则,打印“ -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


输出:
g


时间复杂度: O(N)
辅助空间: O(N)