zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第11章:排序和搜索——题目5

    2014-03-21 21:37

    题目:给定一个字符串数组,但是其中夹杂了很多空串“”,不如{“Hello”, “”, “World”, “”, “”, “”, “Zoo”, “”}请设计一个算法在其中查找字符串。

    解法:要么一次性将其中夹杂的空串去掉,要么在二分查找的过程中逐个跳过空串。反正整体思路仍是二分。

    代码:

     1 // 11.5 Given an array of strings interspersed with empty string ""s. Find out if a target string exists in the string.
     2 #include <iostream>
     3 #include <string>
     4 #include <vector>
     5 using namespace std;
     6 
     7 int main()
     8 {
     9     int i, j, n;
    10     int ns;
    11     string s;
    12     vector<string> v;
    13     int ll, rr, mm;
    14     
    15     while (cin >> n && n > 0) {
    16         cin >> ns;
    17         for (i = 0; i < ns; ++i) {
    18             v.push_back("");
    19         }
    20         for (i = 0; i < n; ++i) {
    21             cin >> s;
    22             v.push_back(s);
    23             cin >> ns;
    24             for (j = 0; j < ns; ++j) {
    25                 v.push_back("");
    26             }
    27         }
    28         cin >> s;
    29         
    30         ll = 0;
    31         while (v[ll] == "") {
    32             ++ll;
    33         }
    34         rr = (int)v.size() - 1;
    35         while (v[rr] == "") {
    36             --rr;
    37         }
    38         while (ll <= rr) {
    39             mm = (ll + rr) / 2;
    40             while (v[mm] == "") {
    41                 // go left or right, either is OK.
    42                 --mm;
    43             }
    44             if (s > v[mm]) {
    45                 ll = mm + 1;
    46                 while (ll <= rr && v[ll] == "") {
    47                     ++ll;
    48                 }
    49             } else if (s < v[mm]) {
    50                 rr = mm - 1;
    51                 while (rr >= ll && v[rr] == "") {
    52                     --rr;
    53                 }
    54             } else {
    55                 break;
    56             }
    57         }
    58         printf("%d
    ", (ll <= rr ? mm : -1));
    59         
    60         v.clear();
    61     }
    62     
    63     return 0;
    64 }
  • 相关阅读:
    【重学计算机】计组D2章:数据表示
    【重学计算机】计组D1章:计算机系统概论
    计算机底层原理杂谈(白话文)
    阿里云安装wordpress遇到的问题
    wordpress数据表结构
    家用计费系统ER图
    java 类中的属性为什么一般都是私有的
    centos 软件库安装
    linux下启动tomcat----Cannot find ./catalina.sh
    jfreechart图表汉字乱码问题解决方案
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3616786.html
Copyright © 2011-2022 走看看