首页 > 解决方案 > 抖动算法

问题描述

有人可以帮我用算法。基本上,如果我有单词 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 谢谢。

标签: javaalgorithm

解决方案


将结果放入一个新的字符串中。这样,您就不必处理每个排列的索引移位。

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;
}

边注:

该方法名称具有误导性,因为它不是凯撒密码算法。使用凯撒密码,您可以更改具有相同偏移量的所有字符值,但它们的索引不会改变。


推荐阅读