-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakeStrangeString.java
More file actions
49 lines (45 loc) · 1.42 KB
/
Copy pathMakeStrangeString.java
File metadata and controls
49 lines (45 loc) · 1.42 KB
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
41
42
43
44
45
46
47
48
49
package basic;
public class MakeStrangeString {
public static String solution(String s) {
char[] words = s.toCharArray();
char[] result = new char[words.length];
boolean toUpper = true;
for (int i = 0; i < words.length; i++) {
char c = words[i];
if (!Character.isAlphabetic(c)) {
result[i] = ' ';
toUpper = true;
continue;
}
if (toUpper) {
result[i] = Character.toUpperCase(c);
toUpper = false;
continue;
}
result[i] = Character.toLowerCase(c);
toUpper = true;
}
return String.valueOf(result);
}
public static String solution_first(String s) {
char[] words = s.toCharArray();
char[] result = new char[words.length];
int oddEvenIndex = 0;
for (int i = 0; i < words.length; i++) {
char c = words[i];
if (c == ' ') {
oddEvenIndex = 0;
result[i] = ' ';
continue;
}
result[i] = makeUpperLowerCase(c, oddEvenIndex++);
}
return String.valueOf(result);
}
private static char makeUpperLowerCase(char c, int oddEvenIndex) {
if (oddEvenIndex % 2 == 0) {
return Character.toUpperCase(c);
}
return Character.toLowerCase(c);
}
}