📌  相关文章
📜  恰好在一个位置上不同的字符串对的计数

📅  最后修改于: 2021-10-27 16:43:35             🧑  作者: Mango

给定一个由等长字符串组成的数组arr[] 。任务是计算恰好在一个位置上不同的字符串对的总数。

例子:

方法1:对于每一个可能的对,检查是否两个字符串中究竟与字符串的单一遍历单个索引位置不同。

方法 2:可以通过以下方式比较两个字符串,以检查它们是否在单个索引位置不同:

下面是上述方法的实现:

C++
// CPP implementation of the approach
#include 
using namespace std;
  
// Function to return the count of same pairs
int pairCount(map &d)
{
    int sum = 0;
    for (auto i : d)
        sum += (i.second * (i.second - 1)) / 2;
  
    return sum;
}
  
// Function to return total number of strings
// which satisfy required condition
int difference(vector &array, int m)
{
    // Dictionary changed will store strings
    // with wild cards
    // Dictionary same will store strings
    // that are equal
    map changed, same;
  
    // Iterating for all strings in the given array
    for (auto s : array)
    {
        // If we found the string then increment by 1
        // Else it will get default value 0
        same[s]++;
  
        // Iterating on a single string
        for (int i = 0; i < m; i++)
        {
            // Adding special symbol to the string
            string t = s.substr(0, i) + "//" + s.substr(i + 1);
  
            // Incrementing the string if found
            // Else it will get default value 0
            changed[t]++;
        }
    }
  
    // Return counted pairs - equal pairs
    return pairCount(changed) - pairCount(same) * m;
}
  
// Driver Code
int main()
{
    int n = 3, m = 3;
    vector array = {"abc", "abd", "bbd"};
    cout << difference(array, m) << endl;
  
    return 0;
}
  
// This code is contributed by
// sanjeev2552


Python3
# Python3 implementation of the approach
  
# Function to return the count of same pairs
def pair_count(d):
    return sum((i*(i-1))//2 for i in d.values())
  
  
# Function to return total number of strings 
# which satisfy required condition
def Difference(array, m):
      
    # Dictionary changed will store strings 
    # with wild cards
    # Dictionary same will store strings 
    # that are equal
    changed, same = {}, {}
      
    # Iterating for all strings in the given array
    for s in array:
          
        # If we found the string then increment by 1 
        # Else it will get default value 0
        same[s]= same.get(s, 0)+1
          
        # Iterating on a single string
        for i in range(m):
            # Adding special symbol to the string
            t = s[:i]+'#'+s[i + 1:]
              
            # Incrementing the string if found 
            # Else it will get default value 0
            changed[t]= changed.get(t, 0)+1
  
    # Return counted pairs - equal pairs
    return pair_count(changed) - pair_count(same)*m
  
# Driver code
if __name__=="__main__":
    n, m = 3, 3
    array =["abc", "abd", "bbd"]
    print(Difference(array, m))


输出:
2

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