Check if a string is a palindrome

后端 未结 30 1570
星月不相逢
星月不相逢 2020-11-28 08:59

I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.

How can I do this?

30条回答
  •  无人及你
    2020-11-28 09:18

    That is non-trivial, there is no built in method to do that for you, you'll have to write your own. You will need to consider what rules you would like to check, like you implicitly stated you accepted reversing of one string. Also, you missed out the middle character, is this only if odd length?

    So you will have something like:

    if(myString.length % 2 = 0)
    {
         //even
         string a = myString.substring(0, myString.length / 2);
         string b = myString.substring(myString.length / 2 + 1, myString.lenght/2);
    
         if(a == b)
               return true;
    
         //Rule 1: reverse
         if(a == b.reverse()) //can't remember if this is a method, if not you'll have to write that too
               return true;
    

    etc, also doing whatever you want for odd strings

提交回复
热议问题