Attempt 1: Compare the string length
class Solution {
public int countPrefixes (String [] words , String s ) {
int targetSize = s .length ();
int count = 0 ;
for (String word : words ) {
int wordSize = word .length ();
if (wordSize > targetSize ) {
continue ;
} else if (wordSize == targetSize ) {
if (word .equals (s )) {
count ++;
}
} else {
if (word .equals (s .substring (0 , wordSize ))) {
count ++;
}
}
}
return count ;
}
}
Runtime: 1 ms (Beats: 54.80%)
Memory: 44.12 MB (Beats: 11.30%)
class Solution {
public int countPrefixes (String [] words , String s ) {
int count = 0 ;
for (String word : words ) {
if (s .indexOf (word ) == 0 ) {
count ++;
}
}
return count ;
}
}
Runtime: 1 ms (Beats: 54.80%)
Memory: 43.12 MB (Beats: 63.47%)
Attempt 3: Use startWith()
class Solution {
public int countPrefixes (String [] words , String s ) {
int count = 0 ;
for (String word : words ) {
if (s .startsWith (word )) {
count ++;
}
}
return count ;
}
}
Runtime: 0 ms (Beats: 100.00%)
Memory: 43.13 MB (Beats: 63.47%)