程序员12期算法擂台

看了12期的讲解,赶紧回来把代码写出来:
//  huiwen.cpp : Defines the entry point for the console application.
//

#include 
" stdafx.h "

void  swap ( char   *   const  s,  int  i,  int  j)
{
    
char temp;
    temp 
= s[i];
    s[i] 
= s[j];
    s[j] 
= temp;
}

int  pseudo_bubble ( char   *   const  s,  int  length)
{
    
int i,j,k;
    
int odd;
    
char alphabet[26];
    
int count=0;

    
for (i=0; i<length; i++)
        alphabet[s[i]
-'a']++;
    
    odd 
= -1;
    
for (i=0; i<sizeof(alphabet); i++)
        
if (alphabet[i] % 2{
            
if (odd = -1// the first 'odd'
                odd = 'a' + i;
            
else // 2 odds
                return -1;
        }


    i
=0;
    
while (s[i] != s[length-1-i]) // until the corresponding element is right
        j = length-1-i;
        
for (k=j-1; k>&& s[k]!=s[i]; k--); // find the corresponding element's location
        if (k == i) {// find nobody -> this is the last 'odd' - closest to the center
            swap(s,k,k+1);
        }
 else {
            
while (k<j) {
                swap(s,k,k
+1); // bubble it out
                count++;
                k
++;
            }

            i
++;
        }

    }


    
return count;
}


int  _tmain( int  argc, _TCHAR *  argv[])
{
    
int x;
    
char s[] = {'a','b','a','c','a','e','b','a','d','c','d'};
    
//{'a','b','a','c','a','b','a','d','c','d'};
    
//{'a','b','a','c','e','b','e','d','c','d'};
    x = pseudo_bubble(s,sizeof(s));
    
if (x==-1)
        printf(
"Impossible");
    
else
        printf(
"%d",x);
    
    
//getchar();
    return 0;
}
开的VS2005写的,显得累赘。。。
找奇数次出现的元素所用的循环可以合并到后来的排序的循环里去的,不过那样,太丑。。。
刚看讲解时以为说的是选择成对字符时可以“左右开弓”?? 但做起来似乎代码很麻烦,所以干脆以左半边为准排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值