TopCorder過去問〜初級1
TopCorderの過去問を日本語で紹介しているブログを見つけた。
topcoderの道1 | プログラミングに自信があるやつこい!!
上記ブログでの回答と違い、シフト文字を自由に定義できるようにしてみた。
【問題】※詳しくは上記リンクを参照 与えられた英語の大文字で構成された文字列の中の文字を、与えられた数字の分だけ左にシフトさせなさい。 たとえば、’C’を2つ左にシフトさせると’A’、’Z’を2つ左にシフトさせると’X’。 与えられる英語の文字列はAからZで、Aの次はZにシフトさせるものとする。 例1) "VQREQFGT" 2 Returns: "TOPCODER"
import java.util.*; class CCipher{ public static String decode(String ciphertest, int shift) { char[] alpha_arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); char[] ciphertest_arr = ciphertest.toCharArray(); for (int i = 0; i < ciphertest_arr.length; i++) { for (int j = 0; j < alpha_arr.length; j++) { if (ciphertest_arr[i] == alpha_arr[j]) { //ciphertest_arrの各文字をalpha_arrを使ってshift分だけずらす for (int k = shift; k > 0; k--) { if (j == 0) { j = alpha_arr.length - 1; } else { j--; } } ciphertest_arr[i] = alpha_arr[j]; } } } return String.valueOf(ciphertest_arr); } public static void main(String args[]){ String ciphertest = "LIPPSASVPH"; int shift = 4; System.out.println(decode(ciphertest, shift)); } }
最近ようやく、Javaのカンが取り戻せてきたかも。