11.5 sort the string array, where empty strings are scattered. Write a method to find the position of the given string.

Source: Internet
Author: User

The binary variation. When we find that the mid element is an empty string, we will also spread to both sides to find an index that is not a blank string as the mid, and continue to perform the second division.

 

public class Solution {    public int search(String[] list, String str) {        if (list == null || list.length == 0 || str == null || str.isEmpty())            return -1;        return searchHelper(list, str, 0, list.length - 1);    }    private int searchHelper(String[] a, String s, int left, int right) {        while (left <= right) {            int mid = left + (right - left) / 2;            if (a[mid].length() == 0) {                int leftNear = mid - 1;                int rightNear = mid + 1;                while (true) {                    if (leftNear < left && rightNear > right)                        return -1;                    if (leftNear >= left && a[leftNear].length() > 0) {                        mid = leftNear;                        break;                    }                    if (rightNear <= right && a[rightNear].length() > 0) {                        mid = rightNear;                        break;                    }                    leftNear--;                    rightNear++;                }            }            if (a[mid].equals(s))                return mid;            else if (a[mid].compareTo(s) < 0) {                left = mid + 1;            } else {                right = mid - 1;            }        }        return -1;    }    public static void main(String[] args) {        String[] stringList = { "apple", "", "", "banana", "", "", "", "carrot", "duck", "", "", "eel", "", "flower" };        System.out.println(new Solution().search(stringList, "carrot"));    }}

 

11.5 sort the string array, where empty strings are scattered. Write a method to find the position of the given string.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.