题解 | #字符串加解密#

字符串加解密

http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

import java.util.*;
import java.util.regex.*;
public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            String plaintext = scanner.nextLine();
            System.out.println(Encrypt(plaintext.toCharArray()));
            String ciphertext = scanner.nextLine();
            System.out.println(Decrypt(ciphertext.toCharArray()));
        }
    }
    
    //进行加密
    public static String Encrypt(char[] plaintextChars){
        StringBuffer buffer = new StringBuffer();
        for(char c:plaintextChars){
            //判断是否是字符
            if(Character.isLetter(c)){
                if(c=='Z')
                    buffer.append("a");
                else if(c=='z')
                    buffer.append("A");
                else if(Character.isLowerCase(c))
                    buffer.append(String.valueOf((char)(c+1)).toUpperCase());
                else if(Character.isUpperCase(c))
                    buffer.append(String.valueOf((char)(c+1)).toLowerCase());
            //判断是否是数字字符
            }else if(Character.isDigit(c)){
                String charStr = String.valueOf((char)(c));
                if(Integer.parseInt(charStr)==9)
                    buffer.append("0");
                else
                    buffer.append(Integer.parseInt(charStr)+1);
            }
        }
        return buffer.toString();
    }
    
    public static String Decrypt(char[] ciphertextChars){
        StringBuffer buffer = new StringBuffer();
        for(char c:ciphertextChars){
            if(Character.isLetter(c)){
                if(c=='A')
                    buffer.append("z");
                else if(c=='a'){
                    buffer.append("Z");
                }
                else if(Character.isLowerCase(c))
                    buffer.append(String.valueOf((char)(c-1)).toUpperCase());
                else if(Character.isUpperCase(c))
                    buffer.append(String.valueOf((char)(c-1)).toLowerCase());
            }else if(Character.isDigit(c)){
                String charStr = String.valueOf((char)(c));
                if(Integer.parseInt(charStr)==0)
                    buffer.append("9");
                else
                    buffer.append(Integer.parseInt(charStr)-1);
            }
        }
        return buffer.toString();
    }
}
全部评论

相关推荐

shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务