检测传入字符串是否存在重复字符,返回boolean

检测传入字符串是否存在重复字符,返回boolean,比如"abc"返回true;"aac"返回false

 

这里提供两种思路:

第一种:

import java.util.HashSet;
import java.util.Set;


public class Test {

    public static boolean checkDifferent2(String iniString) {
        
        //将参数的每一个字符都写入数组
        String[] a = iniString.split("");
        //这里使用Set类下的HashSet对象,该对象是不允许重复的
        Set a1 = new HashSet<String>();
        //将参数数组内的值挨个赋到HashSet中
        for(int i=0; i<a.length; i++) {
            a1.add(a[i]);
        }
        //将HashSet重新转化为数组
        Object[] b = a1.toArray();
        //通过对比两个数组长度来查看是否有重复字符存在
        return a.length == b.length;       
    }
    
}

第二种:

/*
     * 使用String的charAt()方法,利用循环嵌套拿出字符串中每一个字符进行对比
     */
    public static boolean checkDifferent(String iniString) {
        boolean result = false;
        if (iniString.length() > 1) {
            
            for(int i=0; i<iniString.length(); i++) {
                for(int l=0; l<iniString.length(); l++) {
                    if (i==l){
                        continue;
                        } else {
                        if (iniString.charAt(i)!=iniString.charAt(l)) {
                            result = true;
                        } else {
                            return result = false;
                        }
                    }
                }
            }
            
        } else {
            result = true;
        }
        return result;
    }
    

}
posted @ 2016-07-26 16:46  许忠慧  阅读(491)  评论(1编辑  收藏  举报