-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURLify.java
More file actions
49 lines (39 loc) · 1.25 KB
/
Copy pathURLify.java
File metadata and controls
49 lines (39 loc) · 1.25 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 com.java.cci.practice;
public class URLify {
public static void main(String[] args) {
String str = "Mr John Smith ";
char[] arr = str.toCharArray();
int trueLength = findLastCharacter(arr) + 1;
replaceSpaces(arr, trueLength);
String.copyValueOf(arr);
System.out.println("\"" + String.copyValueOf(arr) + "\"");
}
private static void replaceSpaces(char[] arr, int trueLength) {
int spaceCount = 0;
for (int i = 0; i < trueLength; i++) {
if (arr[i] == ' ') {
spaceCount++;
}
}
int index = trueLength + spaceCount * 2;
for (int i = trueLength - 1; i >= 0; i--) {
if (arr[i] == ' ') {
arr[index - 1] = '0';
arr[index - 2] = '2';
arr[index - 3] = '%';
index = index - 3;
} else {
arr[index-1] = arr[i];
index--;
}
}
}
private static int findLastCharacter(char[] arr) {
for (int i = arr.length -1; i >= 0; i--) {
if (arr[i] != ' ') {
return i;
}
}
return -1;
}
}