题解 | #密码验证合格程序#

密码验证合格程序

http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841

就按照题中所给的 1 2 3写3个校验的方法,第一个只是检查字符串长度不用写。
重点写2和3的校验方法
对于2: 可以把字符串转化为字符数组,然后遍历字符数组 如果是大写字母、小写字母、数字、其他字符就把相应的标志置为1 否则默认是0
           最后只需要把4个标志加一起判断是否大于等于3即可。
对于3、使用set集合  首先定义一个统计所有子字符串个数的变量count 初始为0
           2个for循环,注意外层循环只需要进行到一半就够了,通过i和j下标对字符串进行截取存入set中
           同时count不断++,利用set元素不重复的性质,最后比较count和set的大小即可

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            if (s.length() > 8 && check2(s) == 1 && check3(s) == 1) {
                System.out.println("OK");
            } else System.out.println("NG");
        }
    }

    // 2、包括大小写字母.数字.其它符号,以上四种至少三种
    public static int check2(String s){
        int upperCase = 0;
        int lowerCase = 0;
        int num = 0;
        int other = 0;
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c>='0'&&c<='9'){
                num = 1;
            }else if (c>='A'&&c<='Z'){
                upperCase = 1;
            }else if (c>='a'&&c<='z'){
                lowerCase = 1;
            }else other = 1;
        }
        if (num+upperCase+lowerCase+other>=3) return 1;
        return 0;
    }
    // 3、不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
    public static int check3(String s){
        Set<String> set = new HashSet<String>();
        int count =0;
        for (int i = 3; i < s.length()/2+1; i++) {
            for (int j=0;j<s.length()-i;j++){
                String substring = s.substring(j, j + i);
                count++;
                set.add(substring);
            }
        }
        return set.size()<count? 0 : 1;
    }
}


全部评论

相关推荐

点赞 评论 收藏
分享
ming_ri:“很抱歉,您的简历和我们当前的职位需求不是很匹配”
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务