Check if string is palindrome in objective c

前端 未结 10 2212
执念已碎
执念已碎 2021-01-07 02:15

I\'m trying to check if a string is palindrome or not using objective c. I\'m new to programming without any experience in other programming languages so bear with me please

10条回答
  •  一生所求
    2021-01-07 02:32

    Recursive

    - (BOOL)isPaliRec:(NSString*)str :(int)start :(int)end{
        if(start >= end)
           return YES;
        else if([str characterAtIndex:start] != [str characterAtIndex:end])
           return NO;
        else
           return [self isPaliRec:str :++start :--end];
    }
    

    Non Recursive

    - (BOOL)isPali:(NSString*)str{
       for (int i=0; i

    you can call:

    NSString *str = @"arara";
    [self isPaliRec:str :0 :(int)str.length-1];
    [self isPali:str];
    

    Swift 3:

    // Recursive
    func isPaliRec(str: String, start: Int = 0, end: Int = str.characters.count-1) -> Bool {
        if start >= end {
            return true
        } else if str[str.index(str.startIndex, offsetBy: start)] != str[str.index(str.startIndex, offsetBy: end)] {
            return false
        } else {
            return isPaliRec(str: str, start: start+1, end: end-1)
        }
    }
    
    // Non Recursive
    func isPali(str: String) -> Bool {
        for i in 0..

    Also, you can use swift 3 methods like a string extension... It's more elegant. extension sample

提交回复
热议问题