📜  CamelCase模式匹配

📅  最后修改于: 2021-04-17 01:30:44             🧑  作者: Mango

给定一个单词列表,每个单词都遵循CamelCase表示法,任务是打印字典中所有与给定模式匹配的所有单词,这些模式仅由大写字符组成。
例子

方法:
1.遍历每个单词,并保持在给定字符串找到的每个大写字母中散列该单词。
例如:

For string = "GeeksForGeeks"
then the hashing after every uppercase letter found is:
map {
     {G, GeeksForGeeks},
     {GF, GeeksForGeeks},
     {GFG, GeeksForGeeks}
} 

2。为列表中的所有字符串创建哈希之后。在地图中搜索给定的模式,然后打印映射到该模式的所有字符串。

下面是上述方法的实现:

C++
// C++ to find CamelCase Pattern
// matching
#include "bits/stdc++.h"
using namespace std;
 
// Function that prints the camel
// case pattern matching
void CamelCase(vector& words,
               string pattern)
{
 
    // Map to store the hashing
    // of each words with every
    // uppercase letter found
    map > map;
 
    // Traverse the words array
    // that contains all the
    // string
    for (int i = 0; i < words.size(); i++) {
 
        // Intialise str as
        // empty
        string str = "";
 
        // length of string words[i]
        int l = words[i].length();
        for (int j = 0; j < l; j++) {
 
            // For every uppercase
            // letter found map
            // that uppercase to
            // original words
            if (words[i][j] >= 'A'
                && words[i][j] <= 'Z') {
                str += words[i][j];
                map[str].push_back(words[i]);
            }
        }
    }
 
    bool wordFound = false;
 
    // Traverse the map for pattern
    // matching
    for (auto& it : map) {
 
        // If pattern matches then
        // print the corresponding
        // mapped words
        if (it.first == pattern) {
            wordFound = true;
            for (auto& itt : it.second) {
                cout << itt << endl;
            }
        }
    }
 
    // If word not found print
    // "No match found"
    if (!wordFound) {
        cout << "No match found";
    }
}
 
// Driver's Code
int main()
{
    vector words = {
        "Hi", "Hello", "HelloWorld",
        "HiTech", "HiGeek", "HiTechWorld",
        "HiTechCity", "HiTechLab"
    };
 
    // Pattern to be found
    string pattern = "HT";
 
    // Function call to find the
    // words that match to the
    // given pattern
    CamelCase(words, pattern);
 
    return 0;
}


Java
// Java to find CamelCase Pattern
// matching
import java.util.*;
 
class GFG{
  
// Function that prints the camel
// case pattern matching
static void CamelCase(ArrayList words,
               String pattern)
{
  
    // Map to store the hashing
    // of each words with every
    // uppercase letter found
    Map> map = new HashMap>();
  
    // Traverse the words array
    // that contains all the
    // String
    for (int i = 0; i < words.size(); i++) {
  
        // Intialise str as
        // empty
        String str = "";
  
        // length of String words[i]
        int l = words.get(i).length();
        for (int j = 0; j < l; j++) {
  
            // For every uppercase
            // letter found map
            // that uppercase to
            // original words
            if (words.get(i).charAt(j) >= 'A'
                && words.get(i).charAt(j) <= 'Z') {
                str += words.get(i).charAt(j);
                map.put(str,list(map.get(str),words.get(i)));
            }
        }
    }
  
    boolean wordFound = false;
  
    // Traverse the map for pattern
    // matching
    for (Map.Entry> it : map.entrySet()) {
  
        // If pattern matches then
        // print the corresponding
        // mapped words
        if (it.getKey().equals(pattern)) {
            wordFound = true;
            for(String s : it.getValue())
            System.out.print(s +"\n");
             
        }
    }
  
    // If word not found print
    // "No match found"
    if (!wordFound) {
        System.out.print("No match found");
    }
}
  
private static List list(List list, String str) {
    List temp = new ArrayList();
    if(list != null)
        temp.addAll(list);
    temp.add(str);
    return temp;
}
 
// Driver's Code
public static void main(String[] args)
{
    String arr[] = {"Hi", "Hello", "HelloWorld",
            "HiTech", "HiGeek", "HiTechWorld",
            "HiTechCity", "HiTechLab"
        };
 
    ArrayList words = new ArrayList(Arrays.asList(arr));
  
    // Pattern to be found
    String pattern = "HT";
  
    // Function call to find the
    // words that match to the
    // given pattern
    CamelCase(words, pattern);
  
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 to find CamelCase Pattern
# matching
 
# Function that prints the camel
# case pattern matching
def CamelCase(words, pattern) :
 
    # Map to store the hashing
    # of each words with every
    # uppercase letter found
    map = dict.fromkeys(words,None);
 
    # Traverse the words array
    # that contains all the
    # string
    for i in range(len(words)) :
 
        # Intialise str as
        # empty
        string = "";
 
        # length of string words[i]
        l = len(words[i]);
        for j in range(l) :
 
            # For every uppercase
            # letter found map
            # that uppercase to
            # original words
            if (words[i][j] >= 'A' and words[i][j] <= 'Z') :
                string += words[i][j];
                 
                if string not in map :
                    map[string] = [words[i]]
                     
                elif map[string] is None :
                    map[string] = [words[i]]
                     
                else :
                    map[string].append(words[i]);
 
    wordFound = False;
 
    # Traverse the map for pattern
    # matching
    for key,value in map.items() :
 
        # If pattern matches then
        # print the corresponding
        # mapped words
        if (key == pattern) :
            wordFound = True;
            for itt in value :
                print(itt);
 
    # If word not found print
    # "No match found"
    if (not wordFound) :
        print("No match found");
  
 
# Driver's Code
if __name__ == "__main__" :
 
    words = [
        "Hi", "Hello", "HelloWorld",
        "HiTech", "HiGeek", "HiTechWorld",
        "HiTechCity", "HiTechLab"
    ];
 
    # Pattern to be found
    pattern = "HT";
 
    # Function call to find the
    # words that match to the
    # given pattern
    CamelCase(words, pattern);
     
# This code is contributed by AnkitRai01


C#
// C# to find CamelCase Pattern
// matching
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function that prints the camel
// case pattern matching
static void CamelCase(List words,
               String pattern)
{
   
    // Map to store the hashing
    // of each words with every
    // uppercase letter found
    Dictionary> map = new Dictionary>();
   
    // Traverse the words array
    // that contains all the
    // String
    for (int i = 0; i < words.Count; i++) {
   
        // Intialise str as
        // empty
        String str = "";
   
        // length of String words[i]
        int l = words[i].Length;
        for (int j = 0; j < l; j++) {
   
            // For every uppercase
            // letter found map
            // that uppercase to
            // original words
            if (words[i][j] >= 'A'
                && words[i][j] <= 'Z') {
                str += words[i][j];
                if(map.ContainsKey(str))
                    map[str] = list(map[str],words[i]);
                else
                    map.Add(str,list(null,words[i]));
            }
        }
    }
   
    bool wordFound = false;
   
    // Traverse the map for pattern
    // matching
    foreach (KeyValuePair> it in map) {
        // If pattern matches then
        // print the corresponding
        // mapped words
        if (it.Key.Equals(pattern)) {
            wordFound = true;
            foreach(String s in it.Value)
            Console.Write(s +"\n");
              
        }
    }
   
    // If word not found print
    // "No match found"
    if (!wordFound) {
        Console.Write("No match found");
    }
}
   
private static List list(List list, String str) {
    List temp = new List();
    if(list != null)
        temp.AddRange(list);
    temp.Add(str);
    return temp;
}
  
// Driver's Code
public static void Main(String[] args)
{
    String []arr = {"Hi", "Hello", "HelloWorld",
            "HiTech", "HiGeek", "HiTechWorld",
            "HiTechCity", "HiTechLab"
        };
  
    List words = new List(arr);
   
    // Pattern to be found
    String pattern = "HT";
   
    // Function call to find the
    // words that match to the
    // given pattern
    CamelCase(words, pattern);
   
}
}
 
// This code is contributed by Rajput-Ji


C#
using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
    public static void
    PrintMatchingCamelCase(String[] arr, String pattern)
    {
        // Concatenating all array elements
        // using Aggregate function of LINQ
        // putting semicolon as delimiter after each element
        String cctdString
            = arr.Aggregate((i, j) = > i + ';' + j);
        // Map to store the hashing
        // of each words with every
        // uppercase letter found
        Dictionary > map
            = new Dictionary >();
        // temporary Variables
        int charPos = 0;
        int wordPos = 0;
        string strr = string.Empty;
 
        // Traversing through concatenated String
        for (; charPos < cctdString.Length; charPos++) {
            // Identifying if the current Character is
            // CamelCase If so, then adding to map
            // accordingly
            if (cctdString[charPos] >= 'A'
                && cctdString[charPos] <= 'Z') {
                strr += cctdString[charPos];
                if (map.ContainsKey(strr)) {
                    List temp = new List();
                    temp.AddRange(map[strr]);
                    temp.Add(arr[wordPos]);
                    map[strr] = temp;
                }
                else {
                    map.Add(strr, new List{
                                      arr[wordPos] });
                }
            }
            // If delimiter has reached then reseting
            // temporary string also incrementing word
            // position value
            else if (cctdString[charPos] == ';') {
                wordPos++;
                strr = string.Empty;
            }
        }
        // If pattern matches then
        // print the corresponding
        // mapped words
        if (map.ContainsKey(pattern)) {
            foreach(String word in map[pattern])
            {
                Console.WriteLine(word);
            }
        }
        else {
            Console.WriteLine("No Match Found");
        }
    }
 
    // Driver's Code
    public static void Main(String[] args)
    {
        // Array of Words
        String[] arr
            = { "Hi",         "Hello",    "HelloWorld",
                "HiTech",     "HiGeek",   "HiTechWorld",
                "HiTechCity", "HiTechLab" };
 
        // Pattern to be found
        String pattern = "HT";
 
        // Function call to find the
        // words that match to the
        // given pattern
        PrintMatchingCamelCase(arr, pattern);
    }
 
    // This code is contributed by Rishabh Singh
}


输出
HiTech
HiTechWorld
HiTechCity
HiTechLab

时间复杂度: O(N * M),其中N是包含字符串的列表的长度,而M是最长字符串的长度。

高效方法:

  1. 通过串联所有数组元素和分号作为每个数组元素后的定界符来准备字符串。
  2. 遍历连接的字符串并查找大写字符或定界符。
  3. 保留所有大写字符的临时字符串,直到遍历定界符为止。在字典中将此临时字符串作为键添加(如果键不存在),或者在键已经存在的情况下附加单词。
  4. 达到定界符后,请重置临时变量。

下面是上述方法的实现:

C#

using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
    public static void
    PrintMatchingCamelCase(String[] arr, String pattern)
    {
        // Concatenating all array elements
        // using Aggregate function of LINQ
        // putting semicolon as delimiter after each element
        String cctdString
            = arr.Aggregate((i, j) = > i + ';' + j);
        // Map to store the hashing
        // of each words with every
        // uppercase letter found
        Dictionary > map
            = new Dictionary >();
        // temporary Variables
        int charPos = 0;
        int wordPos = 0;
        string strr = string.Empty;
 
        // Traversing through concatenated String
        for (; charPos < cctdString.Length; charPos++) {
            // Identifying if the current Character is
            // CamelCase If so, then adding to map
            // accordingly
            if (cctdString[charPos] >= 'A'
                && cctdString[charPos] <= 'Z') {
                strr += cctdString[charPos];
                if (map.ContainsKey(strr)) {
                    List temp = new List();
                    temp.AddRange(map[strr]);
                    temp.Add(arr[wordPos]);
                    map[strr] = temp;
                }
                else {
                    map.Add(strr, new List{
                                      arr[wordPos] });
                }
            }
            // If delimiter has reached then reseting
            // temporary string also incrementing word
            // position value
            else if (cctdString[charPos] == ';') {
                wordPos++;
                strr = string.Empty;
            }
        }
        // If pattern matches then
        // print the corresponding
        // mapped words
        if (map.ContainsKey(pattern)) {
            foreach(String word in map[pattern])
            {
                Console.WriteLine(word);
            }
        }
        else {
            Console.WriteLine("No Match Found");
        }
    }
 
    // Driver's Code
    public static void Main(String[] args)
    {
        // Array of Words
        String[] arr
            = { "Hi",         "Hello",    "HelloWorld",
                "HiTech",     "HiGeek",   "HiTechWorld",
                "HiTechCity", "HiTechLab" };
 
        // Pattern to be found
        String pattern = "HT";
 
        // Function call to find the
        // words that match to the
        // given pattern
        PrintMatchingCamelCase(arr, pattern);
    }
 
    // This code is contributed by Rishabh Singh
}
输出
HiTech
HiTechWorld
HiTechCity
HiTechLab