golang 遞迴判斷迴文字串

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

判斷迴文字串是個比較經典的問題。

思路就是拿第一個字元和最一個字元比較,如果不等退出,相同的話繼續剛剛的過程,直到第一個字元和最後一個字元相遇或者他們的距離為1時。說明他們是迴文字串。

下面的代碼會忽略空白字元 如"1   1  2 1"會讓為是迴文字串。

golang

package mainimport (    "fmt"    "os"    "strings"    "unicode/utf8")func doPalindrome(s string) bool {    if utf8.RuneCountInString(s) <= 1 {         return true    }       word := strings.Trim(s, "\t \r\n\v")    first, sizeOfFirst := utf8.DecodeRuneInString(word)    last, sizeOfLast := utf8.DecodeLastRuneInString(word)    if first != last {        return false    }       return doPalindrome(word[sizeOfFirst : len(word)-sizeOfLast])}func IsPalindrome(word string) bool {    s := ""    s = strings.Trim(word, "\t \r\n\v")    if len(s) == 0 || len(s) == 1 {         return false    }       return doPalindrome(s)}func main() {    args := os.Args[1:]    for _, v := range args {        ok := IsPalindrome(v)        if ok {            fmt.Printf("%s\n", v)        }       }   }


clang  遞迴版:

#include <stdio.h>#include <string.h>#include <ctype.h>#include <stdint.h>int do_palind(char *first, char *last) {    /*跳過頭部的空白字元*/    while(*first && isspace(*first)) {        first++;    }       /*跳過尾部的空白字元*/    while (first < last && isspace(*last)) {        last--;    }       if (last - first <= 0)        return 1;    if (*first != *last)        return 0;    return do_palind(++first, --last);}int ispalindrome(const char *str) {    if (str[0] == '\0' || str[1] == '\0')        return 0;    //printf("---->%ld\n", strlen(str));    return do_palind((char *)str, (char *)str + strlen(str) - 1); }int main(int argc, char **argv) {    int is;     while (*++argv) {        is = ispalindrome(*argv);        if (is)            printf("%s\n", *argv);    }   }


clang 迴圈版:

#include <stdio.h>#include <string.h>#include <ctype.h>int ispalindrome(const char *str) {    char *last;    if (str[0] == '\0' || str[1] == '\0')        return 0;    last = (char *)str + strlen(str) - 1;    while (str < last) {        while (str < last && isspace(*str)) {            str++;        }           while (str < last && isspace(*last)) {            last--;        }           if (*str != *last)            return 0;        str++;        last--;    }       return 1;}int main(int argc, char **argv) {    int is;     while (*++argv) {        is = ispalindrome(*argv);        if (is) {            printf("%s\n", *argv);        }       }   }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.