第5章 串

串的定义

  • 串是由0个或多个字符组成的有限序列,即字符串。

  • 字符串(在Java中即为Sting类型)的的实现还是相对简单,查看源码即可发现:String实际上是一个char数组。

串的比较

  • 下面是String类equals()方法的实现
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

朴素的模式匹配算法(原始字符串:source,要比较的字符串:compare):

  • 串的定位操作通常被称作串的模式匹配

  • 朴素的模式匹配:简单的说就是,从source的第一个字符开始,逐个与compare的每个字符比较,若匹配成功则返回;若匹配失败则从source的第二个字符开始重新比较,依次类推。

  • 通常情况下,使用朴素的模式匹配即可。

KMP模式匹配算法(还有改进后的KMP算法):

  • 算法相当的有难度,实现起来感觉也很困难,因为在比较之前要获取到比较串compare的相当多的信息,比较麻烦。

  • 有兴趣可以去谷歌一下,我是没什么兴趣了,之前看过一遍,理解起来还是比较容易,但是实现起来就有难度了。

OK,串在这里也就介绍结束了,哈哈!

原文地址:https://www.cnblogs.com/realsoul/p/5882004.html