java - 抖动算法
问题描述
有人可以帮我用算法。基本上,如果我有单词 Hello,我应该取最后一个字母放在第一位,然后取倒数第二个字母放在第二个字母之后,依此类推,取第三个字母放在第三位。它应该是这样的: Word:Hello 1)oHell 2)oHlel 这是我现在拥有的代码。
public static String caesarAlgorithm(
String word) {
char[] arr = word.toCharArray();
int s=arr.length-1;
for (int i=0; i<arr.length/2; i++) {
char temp = arr[i];
char temp1=arr[i+1];
arr[i] = arr[s];
arr[i+1] = temp;
s--;
}
return new String(arr);
}
public static void main(String[] args) {
System.out.print(caesarAlgorithm("Sokolade"));
}
}
在我的情况下,它应该超越 eSdoaklo 谢谢。
解决方案
将结果放入一个新的字符串中。这样,您就不必处理每个排列的索引移位。
public static String caesarAlgorithm(String word) {
char[] arr = word.toCharArray();
String result = "";
for (int i=0; i<arr.length/2; i++) {
// get the i-th letter from the end and put it in the result string
result += arr[arr.length-1-i]; // -1 because index starts at 0
// get the i-th letter from the begining and put it in the result string
result += arr[i];
}
if (arr.length%2 != 0) {
// in case the number of characters is odd, add the middle character to the end of the string
result += arr[arr.length%2+1];
}
return result;
}
边注:
该方法名称具有误导性,因为它不是凯撒密码算法。使用凯撒密码,您可以更改具有相同偏移量的所有字符值,但它们的索引不会改变。
推荐阅读
- java - windows唤醒后如何唤醒Java计时器?
- android - 前台通知服务有时会自行停止,有时会在牛轧糖中自动启动
- angular - Angular Materials Modal:为什么我的变量在订阅中未定义但在地图方法中未定义?
- android - 无文本预览的 NumberPad 键盘
- eclipse - 当我运行我的项目时,这个运行时错误是什么?
- testing - 我如何安装 Spectron 并开始编写脚本?
- maven - 没有 settings.xml 的声纳 Maven 插件
- facebook - 如何在 facebook 分析服务器到服务器中处理用户
- javascript - 如何将 jQuery UI 所有选定范围(不仅是最小值和最大值)加载到数组中
- azure - Hive Table 迁移到不同的环境