[Topic] palindrome string of induction

Disclaimer: This article is a blogger original article, please indicate the source: https://blog.csdn.net/qq_38182125/article/details/89703325

Foreword

In the spring and autumn when trick or trick, manufacturers of pen questions to be investigated string of exceptionally soft spot, but a string of problems in the most special of the palindrome is necessary. In this paper, the author recorded in the written test and a variety of related topics usually brush palindrome problem encountered, on the one hand to facilitate their subsequent review, on the other hand want to help you to look at this article. This article included the following issues:

  • [Huawei] OJ use string - password interception

The problem will be collected from time to time according to complementary topics I encountered.


1. [Huawei] OJ use string - password interception

Title Description

Catcher was a courier MCA countries, he found that the enemy will communicate with some of symmetric cryptographic work, like these ABBA, ABA, A, 123321, but they sometimes add some unrelated characters at the beginning or end to prevent another country break. For example, the following changes ABBA-> 12ABBA, ABA-> ABAKK, 123321-> 51233214. Because the string intercepted too long, and there are many possible scenarios (abaaab can be viewed as aba, or encrypted form baaab of), Cathcer workload is too great, he can only be a computer expert to help, you can Catcher to help find the longest string of valid password it?

Input:

ABBA

Output:

4

problem analysis:

This question is so much to say, in essence, seeking the longest palindrome length of the string substring . For the sake of the longest substring palindromic substantially method can be summarized as three kinds:

  • Violence solved the exhaustive string of seeds each string, and then find the longest palindrome substring. The time complexity is   O ( n 3 ) \ O (n ^ {3})
  • The gap between each character and the character string as the center of the palindrome, and then expand to the sides looking palindromic substring from the center, the longest string obtained by comparing the sub-palindromic. The time complexity is   o ( n 2 ) \ O (n ^ {2})
  • Designed to solve this problem Manacher's Algorithm. The time complexity is   o ( n ) \ O (n) .

Then we were on the Java code above will be achieved in three ways:

1) Solution of violence:

public class Main {

    public static void main(String[] args) {
        String s = "acecaace";
        System.out.println(findLongestPalindrome(s));
    }

    private static boolean isPalindrome(String s){
        int len = s.length();
        for (int i = 0; i < len; i++){
            if (s.charAt(i) != s.charAt(len-1-i)){
                return false;
            }
        }
        return true;
    }

    public static int findLongestPalindrome(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        int max = 0;
        for (int i = 0; i < s.length(); i++){
            for (int j = i+1; j <= s.length(); j++){
                String subString = s.substring(i, j);
                if (isPalindrome(subString) && max < subString.length()){
                    max = subString.length();
                }
            }
        }
        return max;
    }
}

This is a brute force method, the process is nothing to say, very simple, so computational complexity is come: all exhaustive substring in both the for loop, complexity   o ( n 2 ) \ O (n ^ {2}) , immediately after exhaustive but also determines whether or not all sub-strings palindromic substring, determined the complexity of the process   o ( n ) \ O (n) , so that it is stacked together   o ( n 3 ) \ O (n ^ {3}) . Butthe code to write this complexity in an interview means you can go back to such notice, so do not write this code!

2) center expansion method:

Here it is necessary to explain the extended center detection method, such as a string of abcvovovosteps as follows:

Here Insert Picture Description Here Insert Picture DescriptionHere Insert Picture Description

As can be seen from the figure, first to expand a center, then a gap between a, b extend to the center, and then followed by b as the center of expansion, until the last character been traversed. So how should we extend it to the hollow gap? I used here is the manner pad characters, the string after the completion of charging is as follows:
Here Insert Picture Description
Here we use the gap between the character '#' character filled, cleverly solves this problem, the code in this way is as follows below:

public class Main {

    public static void main(String[] args) {
        String s = "abcvovovo";
        System.out.println(findLongestPalindrome(s));
    }
	
	// 预处理字符串的方法,用于填充#
    private static String preHandleString(String s){
        StringBuilder sb = new StringBuilder("#");
        for (int i = 0; i < s.length(); i++){
            sb.append(s.charAt(i)).append('#');
        }
        return sb.toString();
    }

    public static int findLongestPalindrome(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        String str = preHandleString(s);
        int max = 1;
        for (int i = 0; i < str.length(); i++){
            int len = 0;
            int j = i-1, k = i+1;
            // 寻找回文子串
            while (j >= 0 && k < str.length()){
                if (str.charAt(j--) != str.charAt(k++)){
                    break;
                }
                // 回文长度加1(不包含 i 字符)
                ++len;
            }
            if (max < len){
                max = len;
            }
        }
        return max;
    }
}

In this way, we will be able to complexity   o ( n 2 ) \ O (n ^ {2}) under the condition (for overlay and while loops) to complete the calculation of the length of the longest substring palindromic. This method is written not bad, but not outstanding, because there are more good way to solve such problems during the interview.

3).Manacher’s Algorithm:

The algorithm name is called horse-drawn carriage algorithm, designed to solve problems such request string longest palindrome substring, optimization algorithm itself a place that takes full advantage of the information provided by the known palindrome string to achieve the reduction traverse Effect. The recommendations explain algorithm [interview] how to find the site longest palindrome substring of string? For horse-drawn vehicles to explain the algorithm considered a very transparent. Then there is the use of Java code for this algorithm:

public class Main {

    public static void main(String[] args) {
        String s = "abcvovovo";
        System.out.println(findLongestPalindrome(s));
    }

    private static String preHandleString(String s){
        StringBuilder sb = new StringBuilder("#");
        for (int i = 0; i < s.length(); i++){
            sb.append(s.charAt(i)).append('#');
        }
        return sb.toString();
    }

    public static int findLongestPalindrome(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        String str = preHandleString(s);
        int rightSide = 0;
        int rightCenter = 0;
        int[] lens = new int[str.length()];
        int max = 1;

        for (int i = 0; i < str.length(); i++){
            boolean needExpand = true;
            // 如果i点位于rightSide内
            if (i < rightSide){
                // 找出以rightCenter为中心,和i对称的左对称点
                int leftPoint = 2 * rightCenter - i;
                // 直接利用回文的特性得出回文个数
                lens[i] = lens[leftPoint];
                if (i + lens[i] > rightSide){
                    lens[i] = rightSide - i;
                }
                // 根据已知条件计算得出的最长回文小于右边界,则不需要扩展了
                if (i + lens[leftPoint] < rightSide){
                    needExpand = false;
                }
            }
            // 需要进行中心扩展
            if (needExpand){
                while (i - 1 - lens[i] >= 0 && i + 1 + lens[i] < str.length()){
                    if (str.charAt(i - 1 - lens[i]) != str.charAt(i + 1 + lens[i])){
                        break;
                    }
                    ++lens[i];
                }
                rightCenter = i;
                rightSide = i + lens[i];
                if (max < lens[i]){
                    max = lens[i];
                }
            }
        }

        return max;
    }
}

Although there are two cyclic codes, since only a part of the inner loop is not yet matched, and therefore for each character, it only once, the time complexity is   o ( n ) \ O (n) .


I hope this article to help you ~

Guess you like

Origin blog.csdn.net/qq_38182125/article/details/89703325