• 求最大回文前缀的长度问题


    题目描述:
    求一个字符串的最大回文前缀长度。回文是指正反方向读起来都是一样的字符串,比如“abcdcba”就是一个回文。
    输入:
    多行字符串。
    输出:
    最大回文前缀的长度。

    样例输入:
    abc
    abcd
    abcdc
    abcdcb
    abcdcba

    样例输出:
    1
    1
    1
    1
    7

    注意本题是求回文前缀的长度,需要从字符串的首部开始,字符串中间到尾部的部分形成的回文不算。

    一种实现代码如下(Java版):

     1 import java.util.Scanner;
     2 
     3 public class Main {
     4     public static void main(String[] args) {
     5         Scanner in = new Scanner(System.in);
     6         while (in.hasNext()) {
     7            String str = in.nextLine();
     8            System.out.println(getResult(str));
     9         }
    10         in.close();
    11     }
    12     
    13     public static int getResult(String str){
    14         int result = 0;
    15         int i = 0; //第一个指针从字符串首部向后移动
    16         int j = str.length() -1; //第二个指针从字符串尾部向前移动
    17         int hlen = j; //记录回文的长度-1
    18         while (i <= j) {
    19             if (str.charAt(i) == str.charAt(j)) {
    20                 ++i;
    21                 --j;
    22             }else {
    23                 i = 0;
    24                 --j;
    25                 hlen = j;
    26             }
    27         }
    28         result = hlen+1;  //最大回文前缀的长度
    29         return result;
    30     }
    31 }
  • 相关阅读:
    【西瓜书】周志华《机器学习》学习笔记与习题探讨(一)
    01-线性回归算法
    NumPy 字符串函数
    Numpy函数分类
    Excel一对多查询(index+small+if)
    支付机构MRC模
    数据分析方法论
    窗口函数/解析函数
    数据分析
    底层逻辑
  • 原文地址:https://www.cnblogs.com/JiaJoa/p/7801327.html
Copyright © 2020-2023  润新知