码迷,mamicode.com
首页 > 其他好文 > 详细

判断一个字符串通过变化字符的位置,是否可以组成回文

时间:2014-08-18 10:28:13      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

解法就是判断下字符串中是否有某些字符是奇数个,如果这种字符的个数大于1,说明无法组成回文;小于或等于1可以组成回文。

其中用了strlen(),放到for循环里面容易导致程序运行效率下降,比如输入的字符串很大 10^5个字符时

for(int i=0; i<strlen(string); i++)会导致程序运行很慢。改用:

int length = strlen(string); for(int i=0; i<length; i++) 可以很大程度提升效率。

 

bubuko.com,布布扣
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

void findPalind(char *arr)
{
    
    int flag = 0;
    // Find the required answer here. Print Yes or No at the end of this function depending on your inspection of the string
    
    int result[26];
    
    for (int i=0; i<26; i++) {
        result[i] = 0;
    }
    
    int lenth = (int)strlen(arr);
    for (int i=0; i<lenth; i++) {
        int index = (int)*(arr + i) - (int)a;
        if (result[index] == 0) {
            result[index] = 1;
        } else {
            result[index] = 0;
        }
    }
    
    int sum = 0;
    for (int i=0; i<26; i++) {
        sum += result[i];
    }
    
    if (sum >= 2) {
        flag = 1;
    } else {
        flag = 0;
    }
    
    if (flag==0)
        printf("YES\n");
    else
        printf("NO\n");
    
    return;
}
int main() {
    
    char arr[100001];
    scanf("%s",arr);
    findPalind(arr);
    return 0;
}
代码

 

判断一个字符串通过变化字符的位置,是否可以组成回文,布布扣,bubuko.com

判断一个字符串通过变化字符的位置,是否可以组成回文

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/huangzizhu/p/3918801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!