📌  相关文章
📜  查找第一个字符串的字符,该字符存在于第二字符串最小索引

📅  最后修改于: 2021-10-27 09:13:44             🧑  作者: Mango

给定一个字符串str和另一个字符串patt 。查找patt中出现在str 中最小索引处的字符。如果str 中不存在patt字符,则打印“不存在字符”。

例子

资料来源: OLA 采访经历 |设置 12。

朴素的方法:使用两个循环,在str找到 patt的每个字符的第一个索引。打印具有最小索引的字符。如果str 中不存在patt字符,则打印“不存在字符”。

C++
// C++ implementation to find the character in
// first string that is present at minimum index
// in second string
#include 
using namespace std;
 
// function to find the minimum index character
void printMinIndexChar(string str, string patt)
{
    // to store the index of character having
    // minimum index
    int minIndex = INT_MAX;
 
    // lengths of the two strings
    int m = str.size();
    int n = patt.size();
 
    // traverse 'patt'
    for (int i = 0; i < n; i++) {
 
        // for each character of 'patt' traverse 'str'
        for (int j = 0; j < m; j++) {
 
            // if patt[i] is found in 'str', check if
            // it has the minimum index or not. If yes,
            // then update 'minIndex' and break
            if (patt[i] == str[j] && j < minIndex) {
                minIndex = j;
                break;
            }
        }
    }
 
    // print the minimum index character
    if (minIndex != INT_MAX)
        cout << "Minimum Index Character = "
             << str[minIndex];
 
    // if no character of 'patt' is present in 'str'
    else
        cout << "No character present";
}
 
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    string patt = "set";
    printMinIndexChar(str, patt);
    return 0;
}


Java
// Java implementation to find the character in
// first string that is present at minimum index
// in second string
 
public class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // to store the index of character having
        // minimum index
        int minIndex = Integer.MAX_VALUE;
      
        // lengths of the two strings
        int m = str.length();
        int n = patt.length();
      
        // traverse 'patt'
        for (int i = 0; i < n; i++) {
      
            // for each character of 'patt' traverse 'str'
            for (int j = 0; j < m; j++) {
      
                // if patt.charAt(i)is found in 'str', check if
                // it has the minimum index or not. If yes,
                // then update 'minIndex' and break
                if (patt.charAt(i)== str.charAt(j) && j < minIndex) {
                    minIndex = j;
                    break;
                }
            }
        }
      
        // print the minimum index character
        if (minIndex != Integer.MAX_VALUE)
            System.out.println("Minimum Index Character = " +
                                str.charAt(minIndex));
      
        // if no character of 'patt' is present in 'str'
        else
            System.out.println("No character present");
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}


Python3
# Python3 implementation to find the character in
# first that is present at minimum index
# in second String
 
# function to find the minimum index character
def printMinIndexChar(Str, patt):
 
    # to store the index of character having
    # minimum index
    minIndex = 10**9
 
    # lengths of the two Strings
    m =len(Str)
    n =len(patt)
 
    # traverse 'patt'
    for i in range(n):
 
        # for each character of 'patt' traverse 'Str'
        for j in range(m):
 
            # if patt[i] is found in 'Str', check if
            # it has the minimum index or not. If yes,
            # then update 'minIndex' and break
            if (patt[i] == Str[j] and j < minIndex):
                minIndex = j
                break
 
 
 
 
    # print the minimum index character
    if (minIndex != 10**9):
        print("Minimum Index Character = ",Str[minIndex])
 
    # if no character of 'patt' is present in 'Str'
    else:
        print("No character present")
 
 
# Driver code
 
Str = "geeksforgeeks"
patt = "set"
printMinIndexChar(Str, patt)
 
# This code is contributed by mohit kumar 29


C#
// C# implementation to find the character in
// first string that is present at minimum index
// in second string
using System;
 
class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // to store the index of character having
        // minimum index
        int minIndex = int.MaxValue;
     
        // lengths of the two strings
        int m = str.Length;
        int n = patt.Length;
     
        // traverse 'patt'
        for (int i = 0; i < n; i++) {
     
            // for each character of 'patt' traverse 'str'
            for (int j = 0; j < m; j++) {
     
                // if patt.charAt(i)is found in 'str', check if
                // it has the minimum index or not. If yes,
                // then update 'minIndex' and break
                if (patt[i]== str[j] && j < minIndex) {
                    minIndex = j;
                    break;
                }
            }
        }
     
        // print the minimum index character
        if (minIndex != int.MaxValue)
            Console.WriteLine("Minimum Index Character = " +
                                str[minIndex]);
     
        // if no character of 'patt' is present in 'str'
        else
            Console.WriteLine("No character present");
    }
     
    // Driver Methoda
    public static void Main()
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}
// This code is contributed by Sam007


Javascript


C++
// C++ implementation to find the character in first
// string that is present at minimum index in second
// string
#include 
using namespace std;
 
// function to find the minimum index character
void printMinIndexChar(string str, string patt)
{
    // unordered_map 'um' implemented as hash table
    unordered_map um;
 
    // to store the index of character having
    // minimum index
    int minIndex = INT_MAX;
 
    // lengths of the two strings
    int m = str.size();
    int n = patt.size();-
 
    // store the first index of each character of 'str'
    for (int i = 0; i < m; i++)
        if (um.find(str[i]) == um.end())
            um[str[i]] = i;
 
    // traverse the string 'patt'
    for (int i = 0; i < n; i++)
 
        // if patt[i] is found in 'um', check if
        // it has the minimum index or not accordingly
        // update 'minIndex'
        if (um.find(patt[i]) != um.end() &&
            um[patt[i]] < minIndex)
            minIndex = um[patt[i]];
 
    // print the minimum index character
    if (minIndex != INT_MAX)
        cout << "Minimum Index Character = "
             << str[minIndex];
 
    // if no character of 'patt' is present in 'str'
    else
        cout << "No character present";
}
 
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    string patt = "set";
    printMinIndexChar(str, patt);
    return 0;
}


Java
// Java implementation to find the character in
// first string that is present at minimum index
// in second string
 
import java.util.HashMap;
 
public class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // map to store the first index of each character of 'str'
        HashMap hm = new HashMap<>();
         
        // to store the index of character having
        // minimum index
        int minIndex = Integer.MAX_VALUE;
      
        // lengths of the two strings
        int m = str.length();
        int n = patt.length();
      
        // store the first index of each character of 'str'
        for (int i = 0; i < m; i++)
            if(!hm.containsKey(str.charAt(i)))
                hm.put(str.charAt(i),i);
      
        // traverse the string 'patt'
        for (int i = 0; i < n; i++)
            // if patt[i] is found in 'um', check if
            // it has the minimum index or not accordingly
            // update 'minIndex'
            if (hm.containsKey(patt.charAt(i)) &&
                hm.get(patt.charAt(i)) < minIndex)
                minIndex = hm.get(patt.charAt(i));
      
        // print the minimum index character
        if (minIndex != Integer.MAX_VALUE)
            System.out.println("Minimum Index Character = " +
                                str.charAt(minIndex));
      
        // if no character of 'patt' is present in 'str'
        else
            System.out.println("No character present");
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}


Python3
# Python3 implementation to
# find the character in first
# string that is present at
# minimum index in second string
import sys
 
# Function to find the
# minimum index character
def printMinIndexChar(st, patt):
 
    # unordered_map 'um'
    # implemented as hash table
    um = {}
 
    # to store the index of
    # character having minimum index
    minIndex = sys.maxsize
 
    # Lengths of the two strings
    m = len(st)
    n = len(patt)
 
    # Store the first index of
    # each character of 'str'
    for i in range (m):
        if (st[i] not in um):
            um[st[i]] = i
 
    # traverse the string 'patt'
    for i in range(n):
 
        # If patt[i] is found in 'um',
        # check if  it has the minimum
        # index or not accordingly
        # update 'minIndex'
        if (patt[i] in um and
            um[patt[i]] < minIndex):
            minIndex = um[patt[i]]
 
    # Print the minimum index character
    if (minIndex != sys.maxsize):
        print ("Minimum Index Character = ",
                st[minIndex])
 
    # If no character of 'patt'
    # is present in 'str'
    else:
        print ("No character present")
 
# Driver program to test above
if __name__ == "__main__":
 
  st = "geeksforgeeks"
  patt = "set"
  printMinIndexChar(st, patt)
 
# This code is contributed by Chitranayal


C#
// C# implementation to find the character in
// first string that is present at minimum index
// in second string
using System;
using System.Collections.Generic;
 
class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // map to store the first index of
        // each character of 'str'
        Dictionary hm = new Dictionary();
         
        // to store the index of character having
        // minimum index
        int minIndex = int.MaxValue;
     
        // lengths of the two strings
        int m = str.Length;
        int n = patt.Length;
     
        // store the first index of
        // each character of 'str'
        for (int i = 0; i < m; i++)
            if(!hm.ContainsKey(str[i]))
                hm.Add(str[i], i);
     
        // traverse the string 'patt'
        for (int i = 0; i < n; i++)
         
            // if patt[i] is found in 'um',
            // check if it has the minimum index
            // or not, accordingly update 'minIndex'
            if (hm.ContainsKey(patt[i]) &&
                hm[patt[i]] < minIndex)
                minIndex = hm[patt[i]];
     
        // print the minimum index character
        if (minIndex != int.MaxValue)
            Console.WriteLine("Minimum Index Character = " +
                                             str[minIndex]);
     
        // if no character of 'patt' is present in 'str'
        else
            Console.WriteLine("No character present");
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}
 
// This code is contributed by Princi Singh


Javascript


输出

Minimum Index Character = e

时间复杂度:O(mn),其中mn是两个字符串的长度。
辅助空间:O(1)方法二高效方法(Hashing):

  • 创建一个哈希表,其中(key, value)元组表示为(字符, index)元组。
  • str的每个字符的第一个索引存储在哈希表中。
  • 现在,对于patt 的每个字符,检查它是否存在于哈希表中。
    • 如果存在,则从哈希表中获取其索引并更新minIndex (目前遇到的最小索引)。
    • 对于没有匹配的字符打印“No 字符 present”。

哈希表是在 C++ 中使用 unordered_set 实现的。
下图是上述方法的试运行:

下面是上述方法的实现:

C++

// C++ implementation to find the character in first
// string that is present at minimum index in second
// string
#include 
using namespace std;
 
// function to find the minimum index character
void printMinIndexChar(string str, string patt)
{
    // unordered_map 'um' implemented as hash table
    unordered_map um;
 
    // to store the index of character having
    // minimum index
    int minIndex = INT_MAX;
 
    // lengths of the two strings
    int m = str.size();
    int n = patt.size();-
 
    // store the first index of each character of 'str'
    for (int i = 0; i < m; i++)
        if (um.find(str[i]) == um.end())
            um[str[i]] = i;
 
    // traverse the string 'patt'
    for (int i = 0; i < n; i++)
 
        // if patt[i] is found in 'um', check if
        // it has the minimum index or not accordingly
        // update 'minIndex'
        if (um.find(patt[i]) != um.end() &&
            um[patt[i]] < minIndex)
            minIndex = um[patt[i]];
 
    // print the minimum index character
    if (minIndex != INT_MAX)
        cout << "Minimum Index Character = "
             << str[minIndex];
 
    // if no character of 'patt' is present in 'str'
    else
        cout << "No character present";
}
 
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    string patt = "set";
    printMinIndexChar(str, patt);
    return 0;
}

Java

// Java implementation to find the character in
// first string that is present at minimum index
// in second string
 
import java.util.HashMap;
 
public class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // map to store the first index of each character of 'str'
        HashMap hm = new HashMap<>();
         
        // to store the index of character having
        // minimum index
        int minIndex = Integer.MAX_VALUE;
      
        // lengths of the two strings
        int m = str.length();
        int n = patt.length();
      
        // store the first index of each character of 'str'
        for (int i = 0; i < m; i++)
            if(!hm.containsKey(str.charAt(i)))
                hm.put(str.charAt(i),i);
      
        // traverse the string 'patt'
        for (int i = 0; i < n; i++)
            // if patt[i] is found in 'um', check if
            // it has the minimum index or not accordingly
            // update 'minIndex'
            if (hm.containsKey(patt.charAt(i)) &&
                hm.get(patt.charAt(i)) < minIndex)
                minIndex = hm.get(patt.charAt(i));
      
        // print the minimum index character
        if (minIndex != Integer.MAX_VALUE)
            System.out.println("Minimum Index Character = " +
                                str.charAt(minIndex));
      
        // if no character of 'patt' is present in 'str'
        else
            System.out.println("No character present");
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}

蟒蛇3

# Python3 implementation to
# find the character in first
# string that is present at
# minimum index in second string
import sys
 
# Function to find the
# minimum index character
def printMinIndexChar(st, patt):
 
    # unordered_map 'um'
    # implemented as hash table
    um = {}
 
    # to store the index of
    # character having minimum index
    minIndex = sys.maxsize
 
    # Lengths of the two strings
    m = len(st)
    n = len(patt)
 
    # Store the first index of
    # each character of 'str'
    for i in range (m):
        if (st[i] not in um):
            um[st[i]] = i
 
    # traverse the string 'patt'
    for i in range(n):
 
        # If patt[i] is found in 'um',
        # check if  it has the minimum
        # index or not accordingly
        # update 'minIndex'
        if (patt[i] in um and
            um[patt[i]] < minIndex):
            minIndex = um[patt[i]]
 
    # Print the minimum index character
    if (minIndex != sys.maxsize):
        print ("Minimum Index Character = ",
                st[minIndex])
 
    # If no character of 'patt'
    # is present in 'str'
    else:
        print ("No character present")
 
# Driver program to test above
if __name__ == "__main__":
 
  st = "geeksforgeeks"
  patt = "set"
  printMinIndexChar(st, patt)
 
# This code is contributed by Chitranayal

C#

// C# implementation to find the character in
// first string that is present at minimum index
// in second string
using System;
using System.Collections.Generic;
 
class GFG
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // map to store the first index of
        // each character of 'str'
        Dictionary hm = new Dictionary();
         
        // to store the index of character having
        // minimum index
        int minIndex = int.MaxValue;
     
        // lengths of the two strings
        int m = str.Length;
        int n = patt.Length;
     
        // store the first index of
        // each character of 'str'
        for (int i = 0; i < m; i++)
            if(!hm.ContainsKey(str[i]))
                hm.Add(str[i], i);
     
        // traverse the string 'patt'
        for (int i = 0; i < n; i++)
         
            // if patt[i] is found in 'um',
            // check if it has the minimum index
            // or not, accordingly update 'minIndex'
            if (hm.ContainsKey(patt[i]) &&
                hm[patt[i]] < minIndex)
                minIndex = hm[patt[i]];
     
        // print the minimum index character
        if (minIndex != int.MaxValue)
            Console.WriteLine("Minimum Index Character = " +
                                             str[minIndex]);
     
        // if no character of 'patt' is present in 'str'
        else
            Console.WriteLine("No character present");
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}
 
// This code is contributed by Princi Singh

Javascript


输出

Minimum Index Character = e

时间复杂度:O(m + n),其中mn是两个字符串的长度。
辅助空间:O(d),其中d是哈希表的大小,即str中不同字符的数量。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程