# [CareerCup] 11.5 Search Array with Empty Strings 搜索含有空字符串的数组

+关注继续查看

11.5 Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string.
EXAMPLE
Input: find "ball" in {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
Output: 4

class Solution {
public:
int search(vector<string> strings, string str) {
int first = 0, last = strings.size() - 1;
while (first <= last) {
int mid = first + (last - first) / 2;
if (strings[mid].empty()) {
int left = mid - 1, right = mid + 1;
while (true) {
if (left < first && right > last) return -1;
else if (right <= last && !strings[right].empty()) {
mid = right; break;
}
else if (left >= first && !strings[left].empty()) {
mid = left; break;
}
++right;
--left;
}
}
int res = strings[mid].compare(str);
if (res == 0) return mid;
else if (res < 0) first = mid + 1;
else last = mid - 1;
}
return -1;
}
};

本文转自博客园Grandyang的博客，原文链接：搜索含有空字符串的数组[CareerCup] 11.5 Search Array with Empty Strings ，如需转载请自行联系原博主。

json格式的字符串转为json对象遇到特殊字符问题解决

613 0
Oracle 给字符串补空格、补0

1311 0

711 0

1280 0

546 0
.NET C# Tostring format 格式化字符串

1175 0

775 0
+关注

2107

1103

《2021云上架构与运维峰会演讲合集》

《零基础CSS入门教程》

《零基础HTML入门教程》