File tree 2 files changed +43
-10
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +43
-10
lines changed Original file line number Diff line number Diff line change @@ -63,4 +63,38 @@ public boolean validWordAbbreviation(String word, String abbr) {
63
63
}
64
64
}
65
65
}
66
+
67
+ public static class Solution2 {
68
+ public boolean validWordAbbreviation (String word , String abbr ) {
69
+ int aLen = abbr .length ();
70
+ int wLen = word .length ();
71
+ if (aLen > wLen ) {
72
+ return false ;
73
+ }
74
+ int i = 0 ;
75
+ int j = 0 ;
76
+ while (i < wLen && j < aLen ) {
77
+ if (word .charAt (i ) == abbr .charAt (j )) {
78
+ i ++;
79
+ j ++;
80
+ continue ;
81
+ }
82
+
83
+ //now the two chars don't match, then the char in abbr should be a valid digit: 0 < x <= 9
84
+ if (abbr .charAt (j ) == '0' || !Character .isDigit (abbr .charAt (j ))) {
85
+ return false ;
86
+ }
87
+
88
+ //now we count the number of letters that are abbreviated, i.e. get the number from abbr before next letter shows up in abbr
89
+ int num = 0 ;
90
+ while (j < aLen && Character .isDigit (abbr .charAt (j ))) {
91
+ num = num * 10 + (abbr .charAt (j ) - '0' );
92
+ j ++;
93
+ }
94
+
95
+ i += num ;
96
+ }
97
+ return i == wLen && j == aLen ;
98
+ }
99
+ }
66
100
}
Original file line number Diff line number Diff line change 1
1
package com .fishercoder ;
2
2
3
3
import com .fishercoder .solutions ._408 ;
4
- import org .junit .Before ;
5
- import org .junit .BeforeClass ;
6
- import org .junit .Test ;
4
+ import org .junit .jupiter .api .BeforeEach ;
5
+ import org .junit .jupiter .api .Test ;
7
6
8
- import static junit .framework . Assert .assertEquals ;
7
+ import static org . junit .jupiter . api . Assertions .assertEquals ;
9
8
10
9
public class _408Test {
11
10
private static _408 .Solution1 solution1 ;
11
+ private static _408 .Solution2 solution2 ;
12
12
private static Boolean expected ;
13
13
private static Boolean actual ;
14
14
private static String word ;
15
15
private static String abbr ;
16
16
17
- @ BeforeClass
18
- public static void setup () {
17
+ @ BeforeEach
18
+ public void setup () {
19
19
solution1 = new _408 .Solution1 ();
20
- }
21
-
22
- @ Before
23
- public void setupForEachTest () {
20
+ solution2 = new _408 .Solution2 ();
24
21
word = "" ;
25
22
abbr = "" ;
26
23
}
@@ -32,6 +29,8 @@ public void test1() {
32
29
expected = true ;
33
30
actual = solution1 .validWordAbbreviation (word , abbr );
34
31
assertEquals (expected , actual );
32
+ actual = solution2 .validWordAbbreviation (word , abbr );
33
+ assertEquals (expected , actual );
35
34
}
36
35
37
36
@ Test
You can’t perform that action at this time.
0 commit comments