Java工程师笔试题(二)——字符串归并

题目描述

设有两个字符串,先需要将两个字符串合并,合并要求如下:
(1)合并后的字符串中包含两个字符串出现过的所有字符
(2)若有重复字符则只保留一个
(3)结果字符串按26个字母顺序排列
如字符串str1为"asdfsfcv" 和 字符串2为 “bgfdAdac”
则输出结果为 “Aabcdfgsv”

算法来源:某公司校招笔试题
算法分析

这里可以用桶排序的思想,遍历字符串,将不同的字符放入不同的“桶”中,得到计数数组。根据计数数组是否有值,倒出一个加入结果字符串。

Java代码
	public static String mergeStr(String str1 , String str2){
        //声明计数数组 count1计算大写字母出现次数,count2计算小写字符出现次数
        int[] count1 = new int[26];
        int[] count2 = new int[26];
		//计算str1,str2中个字符出现次数
        for (int i = 0; i < str1.length(); i++){
            char c = str1.charAt(i);
            if(c >= 'A' && c <= 'Z'){      //大写字母
                count1[(int)c - 'A'] ++;
            }else if( c>='a'&& c <= 'z' ){ //小写字母
                count2[(int)c - 'a'] ++;
            }
        }
        for (int i = 0; i < str2.length(); i++){
            char c = str2.charAt(i);
            if(c >= 'A' && c <= 'Z'){      
                count1[(int)c - 'A'] ++;
            }else if( c>='a'&& c <= 'z' ){
                count2[(int)c - 'a'] ++;
            }
        }
        //通过计数数组得到结果字符串
        StringBuffer sb = new StringBuffer();
        for (int i = 0 ; i < count1.length ; i++){
            if(count1[i] > 0)
                sb.append( (char)(i + 'A'));
            if (count2[i] > 0)
                sb.append( (char)(i + 'a'));
        }
        return sb.toString();
    }
测试
    public static void main(String[] args) {
        String str1 = "asdfsfcv";
        String str2 = "bgfdAdac";
        System.out.println(mergeStr(str1,str2));
    }

运行结果:

Aabcdfgsv
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值