问题描述

一个单词,可以在其相临的两个字母中插入一个“-”(横杠字符)而形成一个字符串,比如单词cake,可以在相连字母间(不同的位置)拖入“-”,而得到如下字符串:

c-a-k-e
ca-k-e
cak-e
c-ak-e
c-ake
ca-ke
c-a-ke

如果给定任一个单词(作为输入),按上面的规则,在其相临的两个字母中插入一个“-”,要计算出所有可能的形成的字符串(输出),程序要怎么写?

又例如输入单词 cat,输出结果为:

c-a-t
ca-t
c-at

一种遍历算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <iostream>
 
using namespace std;
 
int main()
{
    string word;
    cin>>word;
    int len = word.length()-1;
    long psb = 1;
    for (int i = 0;i < len;i++)
    {
        psb *= 2;
    }
    int *flags = new int[len];
    for (int i = 0;i < psb;i++)
    {
        int temp = i;
        for (int j = 0;j < len;j++)
        {
            flags[j] = temp%2;
            temp = temp/2;
        }
        if(i>0)
        {
            for (int j = 0;j < len;j++)
            {
                cout<<word[j];
                if(flags[j] == 1)cout<<"-";
            }
            cout<<word[word.length()-1]<<endl;
        }
    }
}
Tags: ,.
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)