Just now I saw a friend answering a question in the Chinese programming qualifying round and thought the answer was a little more complicated. The following are my answers:
Original question:
Problem Statement
You are given a string input. You are to find the longest substring of input such that the reversal of the substring is also a substring of input. In case of a tie, return the string
That occurs earliest in input.
Definition
Class:
Reversesubstring
Method:
Findreversed
Parameters:
String
Returns:
String
Method signature:
String findreversed (string input)
(Be sure your method is public)
Notes
-
The substring and its reversal may overlap partially or completely.
-
The entire original string is itself a valid substring (see example 4 ).
Constraints
-
Input will contain between 1 and 50 characters, random Sive.
-
Each character of input will be an uppercase letter ('A'-'Z ').
Examples
0)
"Xbcdefywfedcbz"
Returns: "bcdef"
We see that the reverse of bcdef is fedcb, which appears later in the string.
1)
"XYZ"
Returns: "X"
The best we can do is find a one character substring, So we implement the tie-breaker rule of taking the earliest one first.
2)
"Abcaba"
Returns: "ABA"
The string ABA is a palindrome (it's its own reversal), so it meets the criteria.
3)
"Fdasjkurekjfdfasireyufdhsajyirewq"
Returns: "FDF"
4)
"Abcdcba"
Returns: "abcdcba"
Here, the entire string is its own reversal.
Answer:
1 Public Class Reversesubstring
2 {
3 Public String Findreversed ( String Input)
4 {
5 Int Inputlen = Input. length; // Input length
6 String Tmpstr; // Temporary substring
7
8 For ( Int Tmplen = Inputlen; tmplen > 0 ; Tmplen -- ) // Tmplen indicates the length of the temporary substring, Which is decreased from inputlen.
9 {
10 For ( Int Start = 0 ; Start <= Inputlen - Tmplen; Start ++ ) // Start indicates the start position of tmpstr.
11 {
12 Tmpstr = Input. substring (START, tmplen );
13 If (Input. indexof (getreversedstr (tmpstr )) > = 0 )
14 {
15ReturnTmpstr;
16}
17 }
18 }
19 Return "" ;
20 }
21
22 Public Static String Getreversedstr ( String Str) // Get reverse string
23 {
24 System. Text. stringbuilder reversedstr = New System. Text. stringbuilder ();
25 For ( Int I = 0 ; I < Str. length; I ++ )
26 {
27Reversedstr. insert (0, Str. substring (I,1));
28}
29 Return Reversedstr. tostring ();
30 }
31 }