PTA [Longest Symmetric String] Java

Longest symmetric substring

For a given string, this question requires you to output the length of the longest symmetric substring. For example, given Is PAT&TAP symmetric?, the longest symmetric substring is s PAT&TAP s, so you should output 11.

Input format:

Enter a non-empty string with a length not exceeding 1000 in one line

Output format:

Output the length of the longest symmetric substring in one line

Input sample:

Is PAT&TAP symmetric?

Sample output:

11

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Main {
    
    
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

	public static void main(String[] args) throws IOException {
    
    

		String s = br.readLine();
		int max = 1;
		for (int i = 1; i < s.length() - max / 2; ++i) {
    
    
			int index = 0;
			int num = 0;
			while (i - 1 - index >= 0 && i + index < s.length() && s.charAt(i + index) == s.charAt(i - 1 - index)) {
    
    
				num += 2;
				index++;
			}
			max = max > num ? max : num;
			num = 1;
			while (i - 2 - index >= 0 && i + index < s.length() && s.charAt(i + index) == s.charAt(i - 2 - index)) {
    
    
				num += 2;
				index++;
			}
			max = max > num ? max : num;
		}
		out.print(max);
		out.flush();
	}

}

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_50816725/article/details/109495253