Codewar-009: First Variation on Caesar Cipher

https://www.codewars.com/kata/5508249a98b3234f420000fb/train/javajava

// https://www.codewars.com/kata/5508249a98b3234f420000fb/train/java
package codewar;
import java.util.*;

public class CaesarCipher{
  private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
  
  public static List<String> movingShift(String s, int shift){
    StringBuilder sb = new StringBuilder(s);
    int len = sb.length();
    for(int i = 0; i < len; i++){
      char ch = sb.charAt(i);
      if(Character.isUpperCase(ch)){
        int idx = UPPER.indexOf(ch);
        idx = (idx + shift) % 26;
        sb.setCharAt(i, UPPER.charAt(idx));
      }
      if(Character.isLowerCase(ch)){
        int idx = LOWER.indexOf(ch);
        idx = (idx + shift) % 26;
        sb.setCharAt(i, LOWER.charAt(idx));
      }
      shift++;
    }
    int a = len / 4;
    while(true){
      if(a - 1 < len - 4 * (a - 1)){
        break;
      }
      a--;
    }
    List<String> list = new ArrayList<String>();
    for(int i = 0; i < 4; i++){
      list.add(sb.substring(i * a, i * a + a));
    }
    list.add(sb.substring(4 * a));
    return list;
  }
  
  public static String demovingShift(List<String> s, int shift){
    StringBuilder sb = new StringBuilder();
    for(String x : s){
      sb.append(x);
    }
    int len = sb.length();
    for(int i = 0; i < len; i++){
      char ch = sb.charAt(i);
      if(Character.isUpperCase(ch)){
        int idx = UPPER.indexOf(ch);
        idx = idx - shift >= 0 ? idx - shift : idx - shift + 26;
        sb.setCharAt(i, UPPER.charAt(idx)); 
      }
      if(Character.isLowerCase(ch)){
        int idx = LOWER.indexOf(ch);
        idx = idx - shift >= 0 ? idx - shift : idx - shift + 26;
        sb.setCharAt(i, LOWER.charAt(idx));
      }
      shift = ++ shift % 26;
    }
    return sb.toString();
  }
}
相關文章
相關標籤/搜索