手写实现String.indexOf方法

 public static void main(String[] args) {
        System.out.println(indexOf("de", "acdddefb"));
    }

    public static int indexOf(String target, String source) {
        try {
            if (isEmpty(source) || isEmpty(target)) {
                return -1;
            }
            //这里方式其实挺多的,可以获取索引之后一直往后面比较字符,每个字符都相等就代表存在
            List list = isContains(target.charAt(0), source);
            if (list.isEmpty()) {
                return -1;
            }
            for (Integer index : list) {
                String s = substr(source, index, index + target.length());
                if (target.equals(s)) {
                    return index;
                }
            }
            return -1;
        } catch (Exception e) {
            return -1;
        }

    }

    public static List isContains(char c, String target) {
        List indexList = new ArrayList<>();
        for (int i = 0, length = target.length(); i < length; i++) {
            if (c == target.charAt(i)) {
                indexList.add(i);
            }
        }
        return indexList;
    }


    /**
     * 字符串截取方法
     *
     * @param source 目标字符串
     * @param start  起始索引
     * @param end    结束索引
     * @return
     */
    public static String substr(String source, int start, int end) {
        int length = source.length();
        if (start >= length || start < 0) {
            throw new IndexOutOfBoundsException();
        }
        if (end >= source.length()) {
            end = length;
        }
        StringBuilder result = new StringBuilder();
        for (int i = start; i < end; i++) {
            result.append(source.charAt(i));
        }
        return result.toString();
    }

    public static Boolean isEmpty(String str) {
        return str == null || str.length() <= 0;
    }

 

你可能感兴趣的:(interview)