稀疏数组搜索

编写一种方法,对字符串数组进行排序,将所有稀疏数组搜索合在一起。变位词是指字母相同,但排列不同的字符串。
注意:本题相对原题稍作修改

  • 输入: words = [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”,”dad”, “”, “”], s = “ta”
    输出:-1
    说明: 不存在返回-1。

  • 输入:words = [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”,”dad”, “”, “”], s = “ball”
    输出:4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var findString = function(words, s) {
let [low, high] = [0, words.length - 1];
while (low <= high) {
let mid = (low + high) >> 1;
// 处理空字符串
while (mid > low && words[mid] === '') mid--;
if (words[mid] > s) {
high = mid - 1;
} else if (words[mid] < s) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
};