-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoToOne.java
More file actions
82 lines (66 loc) · 2.13 KB
/
TwoToOne.java
File metadata and controls
82 lines (66 loc) · 2.13 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
##Two to One
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
each taken only once - coming from s1 or s2.
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
* @author changliu
*/
import static org.junit.Assert.*;
import org.junit.Test;
public class TwoToOne {
public static char[] bubbleSort(char[] arr) {
boolean swap = true;
while(swap) {
// initial state to be false, if no swap then it's stable
swap = false;
for (int i = 0; i < arr.length - 1; i++) {
// if swapped, marked as true, since it may need further swap
if (arr[i] > arr[i + 1]) {
char tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swap = true;
}
}
}
return arr;
}
public static String longest(String a, String b) {
String result = "";
for (int i = 0; i < a.length(); i++) {
char s = a.charAt(i);
/**
* very trivial for debugging, here cannot use String.contains(s)
* directly, as it requires CharSequence Use String.contains(""+s),
* since String has CharSequence interface or Use
* String.contains(String.toString(s)) instead. Very Important! You
* don't know the details of the API, that's sooooooo bad!
*/
if (!result.contains("" + s)) {
result += s;
}
}
for (int j = 0; j < b.length(); j++) {
char s = b.charAt(j);
if (!result.contains("" + s)) {
result += s;
}
}
// Why here I cannot use test.toString() to return???
return new String(bubbleSort(result.toCharArray()));
}
@Test
public void test() {
System.out.println("longest Fixed Tests");
assertEquals("aehrsty", TwoToOne.longest("aretheyhere", "yestheyarehere"));
assertEquals("abcdefghilnoprstu", TwoToOne.longest("loopingisfunbutdangerous", "lessdangerousthancoding"));
assertEquals("acefghilmnoprstuy", TwoToOne.longest("inmanylanguages", "theresapairoffunctions"));
}
public static void main(String[] args) {
new TwoToOne().test();
}
}