📌  相关文章
📜  通过仅交换不等字符获得的字符串的不同排列计数

📅  最后修改于: 2021-10-26 06:27:51             🧑  作者: Mango

给定一个字符串,找出可以通过交换两个索引使这些索引处的元素不同而获得的唯一排列的数量。

注意:交换总是在原始字符串执行。

例子:

方法:使用HashMap可以通过以下步骤解决问题:

  1. 创建一个 hashmap 并存储给定字符串的每个字符的频率。
  2. 创建一个变量count来存储给定字符串的字符总数,即count=str.length()和一个变量ans来存储可能的唯一排列数并初始化 ans=0。
  3. 遍历字符串和每个字符:
    • 查找当前索引右侧存在的不同字符的数量。这可以通过用总计数减去该字符的频率来完成。
    • 现在将此计算值添加到ans ,因为这是当前字符可以与之交换以创建唯一排列的字符数。
    • 现在,将当前字符的频率和计数减 1,这样它就不会干扰它右侧出现的相同元素的计算。
  4. 返回 ans+1,因为给定的字符串也是唯一的排列。
C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate total
// number of valid permutations
int validPermutations(string str)
{
    unordered_map m;
 
    // Creating count which is equal to the
    // Total number of characters present and
    // ans that will store the number of unique
    // permutations
    int count = str.length(), ans = 0;
 
    // Storing frequency of each character
    // present in the string
    for (int i = 0; i < str.length(); i++) {
        m[str[i]]++;
    }
    for (int i = 0; i < str.length(); i++) {
        // Adding count of characters by excluding
        // characters equal to current char
        ans += count - m[str[i]];
 
        // Reduce the frequency of the current character
        // and count by 1, so that it cannot interfere
        // with the calculations of the same elements
        // present to the right of it.
        m[str[i]]--;
        count--;
    }
 
    // Return ans+1 (Because the given string
    // is also a unique permutation)
    return ans + 1;
}
 
// Driver Code
int main()
{
    string str = "sstt";
    cout << validPermutations(str);
    return 0;
}


Java
// Java program for the above approach
 
// Importing HashMap class
import java.util.HashMap;
 
class GFG {
 
    // Function to calculate total
    // number of valid permutations
    static int validPermutations(String str)
    {
 
        HashMap m
            = new HashMap();
 
        // Creating count which is equal to the
        // Total number of characters present and
        // ans that will store the number of unique
        // permutations
        int count = str.length(), ans = 0;
 
        // Storing frequency of each character
        // present in the string
        for (int i = 0; i < str.length(); i++) {
            m.put(str.charAt(i),
                  m.getOrDefault(str.charAt(i), 0) + 1);
        }
 
        for (int i = 0; i < str.length(); i++) {
            // Adding count of characters by excluding
            // characters equal to current char
            ans += count - m.get(str.charAt(i));
 
            // Reduce the frequency of the current character
            // and count by 1, so that it cannot interfere
            // with the calculations of the same elements
            // present to the right of it.
            m.put(str.charAt(i), m.get(str.charAt(i)) - 1);
            count--;
        }
 
        // Return ans+1 (Because the given string
        // is also a unique permutation)
        return ans + 1;
    }
 
    public static void main(String[] args)
    {
        String str = "sstt";
 
        System.out.println(validPermutations(str));
    }
}
 
// This code is contributed by rajsanghavi9.


Python3
# Python 3 program for the above approach
 
# Function to calculate total
# number of valid permutations
def validPermutations(str):
    m = {}
 
    # Creating count which is equal to the
    # Total number of characters present and
    # ans that will store the number of unique
    # permutations
    count = len(str)
    ans = 0
 
    # Storing frequency of each character
    # present in the string
    for i in range(len(str)):
        if(str[i] in m):
            m[str[i]] += 1
        else:
            m[str[i]] = 1
    for i in range(len(str)):
       
        # Adding count of characters by excluding
        # characters equal to current char
        ans += count - m[str[i]]
 
        # Reduce the frequency of the current character
        # and count by 1, so that it cannot interfere
        # with the calculations of the same elements
        # present to the right of it.
        m[str[i]] -= 1
        count -= 1
 
    # Return ans+1 (Because the given string
    # is also a unique permutation)
    return ans + 1
 
# Driver Code
if __name__ == '__main__':
    str = "sstt"
    print(validPermutations(str))
 
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
 
// Importing Dictionary class
using System;
using System.Collections.Generic;
 
 
public class GFG {
 
    // Function to calculate total
    // number of valid permutations
    static int validPermutations(String str)
    {
 
        Dictionary m
            = new Dictionary();
 
        // Creating count which is equal to the
        // Total number of characters present and
        // ans that will store the number of unique
        // permutations
        int count = str.Length, ans = 0;
 
        // Storing frequency of each character
        // present in the string
        for (int i = 0; i < str.Length; i++) {
            if(m.ContainsKey(str[i]))
                m[str[i]]=m[str[i]]+1;
            else
                m.Add(str[i], 1);
        }
 
        for (int i = 0; i < str.Length; i++) {
            // Adding count of characters by excluding
            // characters equal to current char
            ans += count - m[str[i]];
 
            // Reduce the frequency of the current character
            // and count by 1, so that it cannot interfere
            // with the calculations of the same elements
            // present to the right of it.
            if(m.ContainsKey(str[i]))
                m[str[i]]=m[str[i]]-1;
            count--;
        }
 
        // Return ans+1 (Because the given string
        // is also a unique permutation)
        return ans + 1;
    }
 
    public static void Main(String[] args)
    {
        String str = "sstt";
 
        Console.WriteLine(validPermutations(str));
    }
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:
5

时间复杂度: O(n)

辅助空间: O(n)

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