日期:2014-05-20  浏览次数:20724 次

算法题:比较字符串是否相等
字符串相等的条件:
1、不区分大小写
2、不区分顺序
比如“aBc”=“ABC”
“abc”=“bac”

要求:要有自己的算法思想。

======
一个方法:
1、先把两个字符串都转化为大写或小写
2、把字符串转化为char数组,然后使用冒泡或比较或其他排序算法实现排序
3、使用equals来判断排序后的连个字符串是否相等

这个方法可行,但是没有体现出做题人自己的算法思想,用的都是系统自带的实现功能。

怎么使用自己的算法来实现这个功能?
------最佳解决方案--------------------
public static boolean equels(String first , String second ) {
first = first.toLowerCase() ;
second = second.toLowerCase() ;

byte[] ch = first.getBytes() ;
byte[] ch1 = second.getBytes() ;
sort(ch);
sort(ch1);

return  new String(ch).equals(new String(ch1));
}


private static void sort(byte[] ch) {
for(int i=0 ; i<ch.length-1 ; i++) {
int lag = ch[i];
int index = i ;
for(int j=i+1 ; j<ch.length ; j++) {
if(lag < ch[j]) {
lag = ch[j];
index = j ;
}
}
ch[index] = ch[i];
ch[i] = (byte) lag ;
}
}


不知合意否?
------其他解决方案--------------------
参考HashSet的哈希算法。

    public static int getHashCode(String str){
int h=0;
for(Character c:str.toUpperCase().toCharArray()){
    h+=c.hashCode();
}
return h;
    }
    public static void main(String[]args)
    {
System.out.println(getHashCode("abc")==getHashCode("aca"));
    }

------其他解决方案--------------------
性能越优化越好~
------其他解决方案--------------------
没有体现出做题人自己的算法思想
----------------
分析的过程,本身就是算法,
用任何程序实现都得用“系统的功能”
------其他解决方案--------------------
他的意思可能是体现的不够彻底,应该有更好地算法实现方法吧,只是我没有想到
引用:
没有体现出做题人自己的算法思想
----------------
分析的过程,本身就是算法,
用任何程序实现都得用“系统的功能”

------其他解决方案--------------------
这个用哈希集合比较常规,分别遍历一次两个串就行了。比排序要好的多。
------其他解决方案--------------------
不知道用哈希集合怎么实现。用HashSet吗?同时还要考虑abcabc和abcaba是不相等的。能否说的详细一点?
引用:
这个用哈希集合比较常规,分别遍历一次两个串就行了。比排序要好的多。

------其他解决方案--------------------

/**
 * 思路
 * 1.比较长度
 * 2.source转换char数组,去desc匹配,然后删除。
 * @param source
 * @param desc
 * @throws Exception
 */
public static void checkString(String source, String desc) throws Exception {
if (source.length() != desc.length()) {
System.out.println("not equal!");
return;
}
source = source.toLowerCase();
desc = desc.toLowerCase();
char[] sourceChars = source.toCharArray();
for (char sourceChar : sourceChars) {