Skip to content

Commit 0bf8de1

Browse files
committed
Added urlify
1 parent 608cdda commit 0bf8de1

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/main/java/com/ctci/arraysandstrings/CheckPermutation.java

+14
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@
88
*/
99
public class CheckPermutation {
1010

11+
/**
12+
* Checks if {@code s1} is a permutation of {@code s2}.
13+
*
14+
* @param s1
15+
* @param s2
16+
* @return
17+
*/
1118
private static boolean isOnePermutationOfOther(String s1, String s2) {
1219
if (s1.length() != s2.length()) {
1320
return false;
@@ -21,6 +28,13 @@ private static boolean isOnePermutationOfOther(String s1, String s2) {
2128
return Arrays.equals(c1, c2);
2229
}
2330

31+
/**
32+
* Checks if {@code s1} is a permutation of {@code s2}.
33+
*
34+
* @param s1
35+
* @param s2
36+
* @return
37+
*/
2438
private static boolean isOnePermutationOfOtherGivenThatStringsContainOnlyAscii(String s1, String s2) {
2539
if (s1.length() != s2.length()) {
2640
return false;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.ctci.arraysandstrings;
2+
3+
/**
4+
* @author rampatra
5+
* @since 19/11/2018
6+
*/
7+
public class URLify {
8+
9+
/**
10+
* We space encode the string such that all spaces in the string are replaced with '%20'. The string {@code str}
11+
* contains extra spaces to accommodate the extra characters.
12+
*
13+
* @param str string with spaces
14+
* @return string with spaces replaced with %20
15+
*/
16+
private static String urlify(String str) {
17+
char[] chars = str.toCharArray();
18+
int curr = chars.length - 1; // we will start backwards so that we don't have to worry about characters we overwrite
19+
int insertIndex = curr;
20+
21+
// move the curr pointer to the last character which isn't a space
22+
while (chars[curr] == 32) {
23+
curr--;
24+
}
25+
26+
while (curr >= 0) {
27+
if (chars[curr] == 32) {
28+
chars[insertIndex--] = '0';
29+
chars[insertIndex--] = '2';
30+
chars[insertIndex--] = '%';
31+
} else {
32+
chars[insertIndex--] = chars[curr];
33+
}
34+
curr--;
35+
}
36+
return String.valueOf(chars);
37+
}
38+
39+
public static void main(String[] args) {
40+
System.out.println(urlify("Mr John Smith "));
41+
System.out.println(urlify("Mr Ram Patra "));
42+
}
43+
}

0 commit comments

Comments
 (0)