StringSplit
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (’_’).
Categories:
similar as GetMiddle
Different part is This kata need return all numbers (included ‘__’)
Add __ in front of loop
public static String[] solution(String s) {
//Write your code here
int l = s.length();
if(l%2 != 0){
s = s+"_";
l += 1;
} String[] result = new String[l/2];
int j = 0;
for(int i =0; i<=l-2;){
substring complexity is O(n)
result[j]=(s.substring(i,i+2));
i+=2;
j++;
} return result;
}
Same as [[GetMiddle]] we can replace substring with charAt
//34ms
public static String[] solution(String s) {
//Write your code here
int l = s.length();
if(l%2 != 0){
s = s+"_";
l += 1;
} String[] result = new String[l/2];
int j = 0;
for(int i =0; i<=l-2;){
result[j]=(s.charAt(i) + "" + s.charAt(i+1));
i+=2;
j++;
} return result;
}}
NOTE!!
String.substring()
have complexity of O(n), be careful when use it!