We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticStringcaesarCipher(Strings,intk){char[]arr="abcdefghijklmnopqrstuvwxyz".toCharArray();// T(26) - > T(1)k%=arr.length;reverse(arr,0,k-1);reverse(arr,k,arr.length-1);reverse(arr,0,arr.length-1);//O(N)StringBuildersb=newStringBuilder();//[c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, a, b]for(inti=0;i<s.length();i++){charch=s.charAt(i);if(Character.isLetter(ch)){if(Character.isLowerCase(ch)){intindex=ch-'a';sb.append(arr[index]);}else{intindex=Character.toLowerCase(ch)-'a';sb.append(Character.toUpperCase(arr[index]));}}else{sb.append(ch);}}returnsb.toString();}staticvoidreverse(char[]arr,intstart,intend){while(start<end){swap(arr,start,end);start++;end--;}}staticvoidswap(char[]arr,intstart,intend){chartemp=arr[start];arr[start]=arr[end];arr[end]=temp;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Caesar Cipher
You are viewing a single comment's thread. Return to all comments →
Beats 100% Java O(N), T(1)