tobackfurture 2009-08-24 13:23
浏览 212
已采纳

一道java面试题,一起研究研究

这道题是这样的,有两个字符串,比较他们中间的值是否相等.注意不是一般的相等!例如
String stra = "ccaaiub"

String strb = "iubacac"
如果出现这样的情况也是相等的!
也就是说两个字符串中字符的个数相等,每个字符出现的次数也是相等的,有什么好的解决方案,考虑下效率上面的因素,因为字符串是不定长的

[b]问题补充:[/b]
如果字符串中穿插的有其它字符,比如数字123等等!给点伪代码,大家都看看!

  • 写回答

6条回答 默认 最新

  • wanghaolovezlq 2009-08-24 14:37
    关注

    [code="java"]
    import java.util.*;

    public class StringCompare
    {

    /**
     * TODO 方法说明
     *
     * @param args
     */
    
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String stra = "ccaaiub" ;
        String strb = "iubacac" ;
        System.out.println(compare(stra,strb));
    }
    
    public static boolean compare(String a, String b)
    {   
        if(a == null && b == null)
            return true;
    
        if(a == null || b == null)
            return false;
    
        if(a.equals(b))
            return true;
    
        if(a.length() != b.length())
            return false;
    
        byte[] byteA = a.getBytes();
        byte[] byteB = b.getBytes();
    
        Map<Byte,Integer> mapA = new HashMap<Byte, Integer>();
        Map<Byte,Integer> mapB = new HashMap<Byte, Integer>();
        Byte btA,btB;
        for(int i=0;i<byteA.length;i++)
        {
            btA = byteA[i];
            btB = byteB[i];
    
            if( mapA.get(btA) == null )
                mapA.put(btA, 1);
            else
                mapA.put(btA, mapA.get(btA) + 1);
    
            if( mapB.get(btB) == null )
                mapB.put(btB, 1);
            else
                mapB.put(btB, mapB.get(btB) + 1);
    
        }
    
        if(mapA.equals(mapB))
            return true;
        else
            return false;
    
    }
    

    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?