字符串重排

给定一个只包含大写英文字母的字符串S,要求你给出对S重新排列的所有不相同的排列数。
如:S为ABA,则不同的排列有ABA、AAB、BAA三种。

#include <stdio.h>
#include <string.h>
int f(int a)
{
    int i;
    int sum=1;
    for(i=1;i<=a;i++)
        sum*=i;
    return sum;
}
int main()
{
    char s[11];
    gets(s);
    int len=strlen(s);
    char a[27],b[27];
    int i,j;
    for(i=0,j=65;i<27;i++,j++)
    {
        a[i]=j;
        b[i]=0;
    }
    for(i=0;i<=len;i++)
        for(j=0;j<27;j++)
            if(s[i]==a[j])b[j]++;
    int sum;
    sum=f(len);
    for(j=0;j<27;j++){sum/=f(b[j]);}
    printf("%d",sum);
    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
字符统计及重排是一个常见的编程问题,可以用Java来实现。下面是一个简单的例子: ```java import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; public class CharacterCountAndReorder { public static void main(String[] args) { String str = "Hello World!"; Map<Character, Integer> charCount = countCharacters(str); System.out.println("字符统计:"); for (Map.Entry<Character, Integer> entry : charCount.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } String reorderedStr = reorderCharacters(charCount); System.out.println("字符重排结果:" + reorderedStr); } // 统计字符串中每个字符的出现次数 public static Map<Character, Integer> countCharacters(String str) { Map<Character, Integer> charCount = new HashMap<>(); for (char c : str.toCharArray()) { charCount.put(c, charCount.getOrDefault(c, 0) + 1); } return charCount; } // 根据字符出现次数重新排列字符串 public static String reorderCharacters(Map<Character, Integer> charCount) { PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> charCount.get(b) - charCount.get(a)); maxHeap.addAll(charCount.keySet()); StringBuilder reorderedStr = new StringBuilder(); while (!maxHeap.isEmpty()) { char c = maxHeap.poll(); int count = charCount.get(c); for (int i = 0; i < count; i++) { reorderedStr.append(c); } } return reorderedStr.toString(); } } ``` 运行以上代码,输出结果为: ``` 字符统计: H: 1 e: 1 l: 3 o: 2 : 1 W: 1 r: 1 d: 1 !: 1 字符重排结果:oooolrldHW! e

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值