CodeWars

记录一些CodeWars上不错的题

手机键盘按键次数问题

1
2
3
4
5
6
7
8
9
10
11
12
public class Keypad {
static String[] keys = {"1", "ABC2", "DEF3", "GHI4", "JKL5",
"MNO6", "PQRS7", "TUV8", "WXYZ9", "*", " 0", "#"};
public static int presses(String phrase) {
int nPresses = 0;
for (char c : phrase.toUpperCase().toCharArray())
for (String s : keys)
nPresses += s.indexOf(c) + 1;
return nPresses;
}
}

数字降序排列

1
2
3
4
5
6
7
public class DescendingOrder {
public static int sortDesc(final int num) {
char[] c = String.valueOf(num).toCharArray();
java.util.Arrays.sort(c);
return Integer.parseInt(new StringBuffer(new String(c)).reverse().toString());
}
}

字符串依每一项中的数字进行排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Order {
public static String order(String words) {
String[] arr = words.split(" ");
StringBuilder result = new StringBuilder("");
for (int i = 0; i < 10; i++) {
for (String s : arr) {
if (s.contains(String.valueOf(i))) {
result.append(s + " ");
}
}
}
return result.toString().trim();
}
}

最大子数组的数值和

1
2
3
4
5
6
7
8
9
10
public class Max {
public static int sequence(int[] arr) {
int m = 0, a = 0, s = 0;
for(int e : arr) {
s += e;
m = Math.min(s, m);
a = Math.max(a, s - m);
}
return a;
}

字符串加密问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Kata {
//正序(加密过程)
public static String encrypt(final String text, int n) {
if (n <= 0 || text == null || text.isEmpty()) {
return text;
}
StringBuilder firstPart = new StringBuilder();
StringBuilder secondPart = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char aChar = text.charAt(i);
if (i % 2 == 1) {
firstPart.append(aChar);
} else {
secondPart.append(aChar);
}
}
return encrypt(firstPart.append(secondPart).toString(), --n);
}
//逆序(解密过程)
public static String decrypt(final String encryptedText, int n) {
if (n <= 0 || encryptedText == null || encryptedText.isEmpty()) {
return encryptedText;
}
StringBuilder text = new StringBuilder();
final int half = encryptedText.length() / 2;
for (int i = 0; i < half; i++) {
text.append(encryptedText.charAt(half + i)).append(
encryptedText.charAt(i));
}
if (encryptedText.length() % 2 == 1) {
text.append(encryptedText.charAt(encryptedText.length() - 1));
}
return decrypt(text.toString(), --n);
}

每隔n位取出字符串的一个字符并组成新字符