408. Valid Word Abbreviation
Given a non-empty strings
and an abbreviationabbr
, return whether the string matches with the given abbreviation.
A string such as"word"
contains only the following valid abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string"word"
. Any other string is not a valid abbreviation of"word"
.
Note:
Assumes
contains only lowercase letters andabbr
contains only lowercase letters and digits.
Example 1:
Given
s = "internationalization",
abbr = "i12iz4n":
Return true.
Example 2:
Given
s = "apple",
abbr = "a2e":
Return false.
@Test
public void test0(){
word = "..";
abbr = "2";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
public void test1(){
word = "internationalization";
abbr = "i12iz4n";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test2(){
word = "apple";
abbr = "a2e";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test3(){
word = "internationalization";
abbr = "i5a11o1";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test4(){
word = "hi";
abbr = "1";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test5(){
word = "a";
abbr = "1";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test6(){
word = "a";
abbr = "2";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test7(){
word = "hi";
abbr = "1i";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test8(){
word = "hi";
abbr = "3";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test9(){
word = "hi";
abbr = "11";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test10(){
word = "word";
abbr = "1o1d";
expected = true;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
@Test
public void test11(){
word = "abbreviation";
abbr = "a010n";
expected = false;
actual = test.validWordAbbreviation(word, abbr);
assertEquals(expected, actual);
}
class Solution(object):
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
substitute = re.sub('([1-9]\d*)', r'.{\1}', abbr) + '$' # end of string to garanttee it covers the entire string
# print(re.match(substitute, word).group(0))
return bool(re.match(substitute, word))