题解 | #字符串加密#

字符串加密

http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3

和题目有所不同, 下面的代码. 支持大小写都存在的用例.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String key = scan.nextLine();
            String s = scan.nextLine();
            char[] arr = entryption(key);//被加密后的字母顺序
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                boolean isUpper = false;
                if (c == ' ') {
                    sb.append(c);
                    continue;
                } 
                if (c >= 'A' && c <= 'Z') { 
                    c = (char) (c - 'A' + 'a');
                    isUpper = true;
                }
                if (isUpper) sb.append(String.valueOf(arr[c - 'a']).toUpperCase());
                else sb.append(arr[c - 'a']);
            }
            System.out.println(sb.toString());
        }
    }
    public static char[] entryption(String s) {
        HashSet<Character> set = new HashSet<>();
        List<Character> list = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                c = (char) (c - 'A' + 'a');
            }
            if (set.contains(c)) continue;
            set.add(c);
            list.add(c);
        }
        char[] res = new char[26];
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            res[index++] = list.get(i);
        }
        for (int i = (int) 'a'; i <= (int) 'z'; i++) {
            char c = (char) i;
            if (set.contains(c)) continue;
            res[index++] = c;
        }
        return res;
    }
}
全部评论

相关推荐

09-29 17:44
已编辑
蔚来_测(准入职员工)
//鲨鱼辣椒:见不了了我实习了四个月上周再投筛选了一天就给我挂了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务