Skip to content

Commit 059d9a9

Browse files
committedJun 4, 2024·
add a solution for 408
1 parent b386c27 commit 059d9a9

File tree

2 files changed

+43
-10
lines changed

2 files changed

+43
-10
lines changed
 

‎src/main/java/com/fishercoder/solutions/_408.java

+34
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,38 @@ public boolean validWordAbbreviation(String word, String abbr) {
6363
}
6464
}
6565
}
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+
}
66100
}

‎src/test/java/com/fishercoder/_408Test.java

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
package com.fishercoder;
22

33
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;
76

8-
import static junit.framework.Assert.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
98

109
public class _408Test {
1110
private static _408.Solution1 solution1;
11+
private static _408.Solution2 solution2;
1212
private static Boolean expected;
1313
private static Boolean actual;
1414
private static String word;
1515
private static String abbr;
1616

17-
@BeforeClass
18-
public static void setup() {
17+
@BeforeEach
18+
public void setup() {
1919
solution1 = new _408.Solution1();
20-
}
21-
22-
@Before
23-
public void setupForEachTest() {
20+
solution2 = new _408.Solution2();
2421
word = "";
2522
abbr = "";
2623
}
@@ -32,6 +29,8 @@ public void test1() {
3229
expected = true;
3330
actual = solution1.validWordAbbreviation(word, abbr);
3431
assertEquals(expected, actual);
32+
actual = solution2.validWordAbbreviation(word, abbr);
33+
assertEquals(expected, actual);
3534
}
3635

3736
@Test

0 commit comments

Comments
 (0)
Please sign in to comment.