每日一道算法题 12(2023-12-20)

发布时间:2023年12月20日

?字符串加密
?题目
给出原文字符串str,通过对字符串的每个字母进行改变来实现加密,加密方式是在每一个字母str[i]偏移特定数组元素a[i]的量。
数组a的前三位已经赋值:a[0]=1,a[1]=2,a[2]=4,
当i>=3时,数组元素a[i]=a[i-1]+a[i-2]+a[i-3]。
例如:原文abcde加密后bdgkr,其中偏移量分别是1,2,4,7,13。
a[i] 的偏移量超过26后,就不是字符串。所以需要处理
公式为 (s[i]+a[i]-97)%26+97 计算出还是小写字符。

单n 为50时,偏移量会达到10562230626642 超过Integer 所以用long


输入描述:
第一行是整数n(1<=n<=1000),表示n组测试数据。 每组数据包含一行,原文str(只含有小写字母,长度大于0小于50)。
输出描述:
每组测试数据输出一行,表示密文。
示例

输入
1
xy
输出
ya

示例2
输入
2
xy
abcde
输出
ya
bdgkr

package com.tarena.test.B20;

import java.util.Scanner;

/**
?* @author Administrator
?*
?*/
public class B21 {

?? ?public static void main(String[] args) {
?? ??? ?try(Scanner sc = new Scanner(System.in)){
?? ??? ??? ?int n = sc.nextInt();
?? ??? ??? ?String[] lines = new String[n];
?? ??? ??? ?for(int i=0;i<n;i++) {
?? ??? ??? ??? ?lines[i] = sc.next();
?? ??? ??? ?}
?? ??? ??? ?
?? ??? ??? ?for(int i= 0;i<n;i++) {
?? ??? ??? ??? ?System.out.println(resultStr(lines[i]));
?? ??? ??? ?}
?? ??? ?}
?? ?}
?? ?
?? ?public static String resultStr(String str) {
?? ??? ?int n = str.length();
?? ??? ?//初始化a数组
?? ??? ?long[] a = new long[n];
?? ??? ?if(n>0) a[0] = 1;
?? ??? ?if(n>1) a[1] = 2;
?? ??? ?if(n>2) a[2] = 4;
?? ??? ?if(n>3) {
?? ??? ??? ?for(int i=3;i<n;i++) {
?? ??? ??? ??? ?a[i]=a[i-1]+a[i-2]+a[i-3];
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//为字符串的每一个字符添加a[i]偏移量
?? ??? ?char[] arr = str.toCharArray();
?? ??? ?for(int i=0;i<n;i++) {
?? ??? ??? ?arr[i]= (char)((a[i]+arr[i]-97)%26+97);
?? ??? ?}
?? ??? ?return new String(arr);
?? ?}
}
了解知识点

1、ASCCII 大写字母时 65~90,小写字母是97~122,数字是48~57

文章来源:https://blog.csdn.net/zhen340417593/article/details/135038165
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。