字符串算法

中心扩展法(最长回文串)

public class LongestPalindrome {

  public static void main(String[] args) {
    LongestPalindrome longestPalindrome = new LongestPalindrome();
    System.out.println(longestPalindrome.longestPalindrome("abdbdc"));
  }

  // 判断是否是回文串
  public boolean isMatch(String s) {
    int len = s.length();
    for (int i = 0; i < len / 2; i++) {
      // 根据中心判断是否相等
      if (s.charAt(i) != s.charAt(len - i - 1)) {
        return false;
      }
    }
    return true;
  }

  public String longestPalindrome(String s) {
    String result = "";
    int max = 0;
    int len = s.length();
    for (int i = 0; i < len; i++)
     for (int j = i + 1; j <= len; j++) {
      // 判断每一段子串
      String str = s.substring(i, j);
      if (isMatch(str) && str.length() > max) {
        result = s.substring(i, j);
        // 记录回文串的最大长度
        max = Math.max(max, result.length());
      }
    }
    return result;
  }
}

 KMP算法

next数组

字符串最长的公共前后缀

 public static void getNextArr(int[] next, String s) {
        int j = 0;//j表示前缀起始位置
        next[0] = 0;
        //i表示后缀起始位置
        for(int i = 1; i < s.length(); i++) {
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = next[j - 1];
            }
            if (s.charAt(i) == s.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
    }

匹配

public static int getIndexOf(String haystack, String needle) {
        if (haystack == null){
            return -1;
        }
        if (needle == null || needle.length() == 0) {
            return -1;
        }
        int[] next = new int[needle.length()];
        getNextArr(next, needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while(j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length() ) {
                return (i - needle.length() + 1);
            }
        }
        return -1;
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值