Question requirements:
Design a program in Java to implement the symmetric number of a string, such as the string "effeghg", which contains three symmetric characters: "FF", "effe", and "GHG, so 3 is returned.
My idea is to traverse this string,
First, select the first character as the header and traverse the string from the end,
If the start and end of the string are the same, the intermediate string is used for recursion.
The result is obtained after recursion,
Continue to push the header back to 1 bit, and then traverse from the end of the string forward,
In this loop, when the end is equal to the header, the outermost loop is exited and the result is output.
Specific implementation:
- /**
- * @ Author bzwm
- *
- */
- Public class findpolicrystr {
- /**
- * Find the number of symmetric substrings in the string
- * @ Param orgstr
- * @ Return
- */
- Public static int findsymmetrystr (string orgstr ){
- // Result Initialization
- Int COUNT = 0;
- // Search when the input string is not null and the length is greater than 1; otherwise, 0 is returned directly.
- If (orgstr! = NULL & orgstr. Length ()> 1 ){
- // Obtain the length of the input string
- Int size = orgstr. Length ();
- // Index of the first character of the string
- Int head;
- // The "tail" Character index of the string from the back to the front, that is, the current character index
- Int current;
- // The first character of the string
- Char hstr;
- // The "last" character of the string from the back to the front
- Char CSTR;
- // Traverse strings from the beginning
- For (Head = 0; head <size; head ++ ){
- // Get the first character
- Hstr = orgstr. charat (head );
- // Point to the end of the input string
- Current = size-1;
- // Exit the loop when the last character index is equal to the first character index
- While (current> head ){
- // Get the last character
- CSTR = orgstr. charat (current );
- // If the start and end characters are equal, continue to judge
- If (hstr = CSTR ){
- // Retrieve the substring in the middle of the header and tail and analyze it
- String newstr = orgstr. substring (Head + 1, current );
- // Recursion is performed if the length of the substring is greater than 1
- If (newstr. Length ()> 1)
- // Recursively obtain the number of symmetric strings in this substring
- Count + = findsymmetrystr (newstr );
- // If the substring contains only one or zero characters, it indicates that the original header and tail character form a symmetric string
- Else
- Count ++;
- // Push the index of the last character to the first place
- Current --;
- }
- // If the start and end characters are not equal, the index of the end character is pushed forward by one character
- Else {
- Current --;
- }
- }
- }
- }
- Return count;
- }
- // Test the program
- Public static void main (string ARGs []) {
- Int COUNT = findjavasrystr ("cddcbcbeffeghg ");//
- System. Out. println ("handle ry string count is:" + count );
- }
- }