📌  相关文章
📜  计算可以通过交换给定数组中字符串对的第一个字符获得的新字符串对

📅  最后修改于: 2021-09-07 02:04:18             🧑  作者: Mango

给定的阵列ARR []N字符串,任务是找到一对字符串中不存在任何对所形成的阵列中(ARR [I],编曲[j]的)通过交换字符串的第一字符arr[i]arr[j]

例子:

朴素方法:解决给定问题的最简单方法是生成所有字符串对,并为每对交换两个字符串的第一个字符,如果两个字符串都存在于数组中,则计算这一对。检查所有对后,打印获得的计数值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count new pairs of strings
// that can be obtained by swapping first
// characters of any pair of strings
void countStringPairs(string a[], int n)
{
 
    // Stores the count of pairs
    int ans = 0;
 
    // Generate all possible pairs of
    // strings from the array arr[]
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Stores the current
            // pair of strings
            string p = a[i], q = a[j];
 
            // Swap the first characters
            if (p[0] != q[0]) {
 
                swap(p[0], q[0]);
                int flag1 = 0;
                int flag2 = 0;
 
                // Check if they are already
                // present in the array or not
                for (int k = 0; k < n; k++) {
 
                    if (a[k] == p) {
                        flag1 = 1;
                    }
                    if (a[k] == q) {
                        flag2 = 1;
                    }
                }
 
                // If both the strings
                // are not present
                if (flag1 == 0 && flag2 == 0) {
 
                    // Increment the ans
                    // by 1
                    ans = ans + 1;
                }
            }
        }
    }
 
    // Print the resultant count
    cout << ans;
}
 
// Driver Code
int main()
{
    string arr[] = { "good", "bad", "food" };
    int N = sizeof(arr) / sizeof(arr[0]);
    countStringPairs(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to count new pairs of strings
// that can be obtained by swapping first
// characters of any pair of strings
static void countStringPairs(String a[], int n)
{
     
    // Stores the count of pairs
    int ans = 0;
 
    // Generate all possible pairs of
    // strings from the array arr[]
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // Stores the current
            // pair of strings
            char p[] = a[i].toCharArray();
            char q[] = a[j].toCharArray();
 
            // Swap the first characters
            if (p[0] != q[0])
            {
                char temp = p[0];
                p[0] = q[0];
                q[0] = temp;
                int flag1 = 0;
                int flag2 = 0;
 
                // Check if they are already
                // present in the array or not
                for(int k = 0; k < n; k++)
                {
                    if (a[k].equals(new String(p)))
                    {
                        flag1 = 1;
                    }
                    if (a[k].equals(new String(q)))
                    {
                        flag2 = 1;
                    }
                }
 
                // If both the strings
                // are not present
                if (flag1 == 0 && flag2 == 0)
                {
 
                    // Increment the ans
                    // by 1
                    ans = ans + 1;
                }
            }
        }
    }
 
    // Print the resultant count
    System.out.println(ans);
}
 
// Driver Code
public static void main(String[] args)
{
    String arr[] = { "good", "bad", "food" };
    int N = arr.length;
     
    countStringPairs(arr, N);
}
}
 
// This code is contributed by Kingash


Python3
# python 3 program for the above approach
 
# Function to count new pairs of strings
# that can be obtained by swapping first
# characters of any pair of strings
def countStringPairs(a, n):
   
    # Stores the count of pairs
    ans = 0
 
    # Generate all possible pairs of
    # strings from the array arr[]
    for i in range(n):
        for j in range(i + 1, n, 1):
           
            # Stores the current
            # pair of strings
            p = a[i]
            q = a[j]
 
            # Swap the first characters
            if (p[0] != q[0]):
                p = list(p)
                q = list(q)
                temp = p[0]
                p[0] = q[0]
                q[0] = temp
 
                p = ''.join(p)
                q = ''.join(q)
                flag1 = 0
                flag2 = 0
 
                # Check if they are already
                # present in the array or not
                for k in range(n):
                    if (a[k] == p):
                        flag1 = 1
                    if (a[k] == q):
                        flag2 = 1
 
                # If both the strings
                # are not present
                if (flag1 == 0 and flag2 == 0):
                   
                    # Increment the ans
                    # by 1
                    ans = ans + 1
 
    # Print the resultant count
    print(ans)
 
# Driver Code
if __name__ == '__main__':
    arr = ["good", "bad", "food"]
    N = len(arr)
    countStringPairs(arr, N)
 
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C # program for the above approach
using System;
class GFG {
 
    // Function to count new pairs of strings
    // that can be obtained by swapping first
    // characters of any pair of strings
    static void countStringPairs(string[] a, int n)
    {
 
        // Stores the count of pairs
        int ans = 0;
 
        // Generate all possible pairs of
        // strings from the array arr[]
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Stores the current
                // pair of strings
                char[] p = a[i].ToCharArray();
                char[] q = a[j].ToCharArray();
 
                // Swap the first characters
                if (p[0] != q[0]) {
                    char temp = p[0];
                    p[0] = q[0];
                    q[0] = temp;
                    int flag1 = 0;
                    int flag2 = 0;
 
                    // Check if they are already
                    // present in the array or not
                    for (int k = 0; k < n; k++) {
                        if (a[k].Equals(new string(p))) {
                            flag1 = 1;
                        }
                        if (a[k].Equals(new string(q))) {
                            flag2 = 1;
                        }
                    }
 
                    // If both the strings
                    // are not present
                    if (flag1 == 0 && flag2 == 0) {
 
                        // Increment the ans
                        // by 1
                        ans = ans + 1;
                    }
                }
            }
        }
 
        // Print the resultant count
        Console.WriteLine(ans);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string[] arr = { "good", "bad", "food" };
        int N = arr.Length;
 
        countStringPairs(arr, N);
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count newly created pairs
// by swapping the first characters of
// any pairs of strings
void countStringPairs(string a[], int n)
{
 
    // Stores the count all possible
    // pair of strings
    int ans = 0;
 
    // Push all the strings
    // into the Unordered Map
    unordered_map s;
    for (int i = 0; i < n; i++) {
        s[a[i]]++;
    }
 
    // Generate all possible pairs of
    // strings from the array arr[]
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Store the current
            // pair of strings
            string p = a[i];
            string q = a[j];
 
            // Swap the first character
            if (p[0] != q[0]) {
                swap(p[0], q[0]);
 
                // Check if both string
                // are not present in map
                if (s.find(p) == s.end()
                    && s.find(q) == s.end()) {
                    ans++;
                }
            }
        }
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    string arr[] = { "good", "bad", "food" };
    int N = sizeof(arr) / sizeof(arr[0]);
    countStringPairs(arr, N);
 
    return 0;
}


Python3
# Python3 program for the above approach
 
# Function to count newly created pairs
# by swapping the first characters of
# any pairs of strings
def countStringPairs(a, n):
 
    # Stores the count all possible
    # pair of strings
    ans = 0
 
    # Push all the strings
    # into the Unordered Map
    s = {}
    for i in range(n):
        s[a[i]] = s.get(a[i], 0) + 1
 
    # Generate all possible pairs of
    # strings from the array arr[]
    for i in range(n):
        for j in range(i + 1, n):
             
            # Store the current
            # pair of strings
            p = [i for i in a[i]]
            q = [j for j in a[j]]
 
            # Swap the first character
            if (p[0] != q[0]):
                p[0], q[0] = q[0], p[0]
                 
                # Check if both string
                # are not present in map
                if (("".join(p) not in s) and
                    ("".join(q) not in s)):
                    ans += 1
                     
    # Print the result
    print (ans)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "good", "bad", "food" ]
    N = len(arr)
     
    countStringPairs(arr, N)
 
# This code is contributed by mohit kumar 29


输出:
2

时间复杂度: O(N 3 )
辅助空间: O(M),其中 M 是数组中存在的字符串的最大大小,A[]

高效的方法:上述方法也可以通过使用Hashing的概念进行优化。请按照以下步骤解决问题:

  • 初始化一个变量,比如ans0来存储字符串对的可能计数。
  • 初始化一个 HashMap,比如M来存储数组arr[] 中存在的所有字符串。
  • 遍历数组arr[]并增加arr[i]M 中的出现次数。
  • 使用变量i[0, N – 1]范围内迭代并执行以下步骤:
    • 使用变量j在范围[i + 1, N – 1] 中迭代并执行以下步骤:
      • 将当前字符串对存储在两个临时字符串,比如pq
      • 交换字符串pq的第一个字符。
      • 如果字符串pq都不存在于 HashMap M 中,则将ans的值增加1
  • 完成以上步骤后,打印ans的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count newly created pairs
// by swapping the first characters of
// any pairs of strings
void countStringPairs(string a[], int n)
{
 
    // Stores the count all possible
    // pair of strings
    int ans = 0;
 
    // Push all the strings
    // into the Unordered Map
    unordered_map s;
    for (int i = 0; i < n; i++) {
        s[a[i]]++;
    }
 
    // Generate all possible pairs of
    // strings from the array arr[]
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Store the current
            // pair of strings
            string p = a[i];
            string q = a[j];
 
            // Swap the first character
            if (p[0] != q[0]) {
                swap(p[0], q[0]);
 
                // Check if both string
                // are not present in map
                if (s.find(p) == s.end()
                    && s.find(q) == s.end()) {
                    ans++;
                }
            }
        }
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    string arr[] = { "good", "bad", "food" };
    int N = sizeof(arr) / sizeof(arr[0]);
    countStringPairs(arr, N);
 
    return 0;
}

蟒蛇3

# Python3 program for the above approach
 
# Function to count newly created pairs
# by swapping the first characters of
# any pairs of strings
def countStringPairs(a, n):
 
    # Stores the count all possible
    # pair of strings
    ans = 0
 
    # Push all the strings
    # into the Unordered Map
    s = {}
    for i in range(n):
        s[a[i]] = s.get(a[i], 0) + 1
 
    # Generate all possible pairs of
    # strings from the array arr[]
    for i in range(n):
        for j in range(i + 1, n):
             
            # Store the current
            # pair of strings
            p = [i for i in a[i]]
            q = [j for j in a[j]]
 
            # Swap the first character
            if (p[0] != q[0]):
                p[0], q[0] = q[0], p[0]
                 
                # Check if both string
                # are not present in map
                if (("".join(p) not in s) and
                    ("".join(q) not in s)):
                    ans += 1
                     
    # Print the result
    print (ans)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "good", "bad", "food" ]
    N = len(arr)
     
    countStringPairs(arr, N)
 
# This code is contributed by mohit kumar 29
输出:
2

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live