Codewar-009: First Variation on Caesar Cipher

原创
2016/12/07 18:40
阅读数 171

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

// 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();
  }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部