📄 shuangseqiusf.txt
字号:
发表于:2007-12-03 03:50:296楼 得分:0
再来个非常难理解的,算法有些二进制的知识,效率不高,且只适合数字元素少的情况。
优点是代码精简巧妙,面试考官八成看不明白,自叹不如而录取你。
C# codeusing System;
using System.Text;
using System.Collections.Generic;
namespace SplitStringToSingles
{
class Program
{
public static string[] ToSingle(string Number) //格式 01 02 03 04 05 06 07
{
string[] words = Number.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder singles = new StringBuilder();
int Max = 1 << words.Length;
int[] Mark = new int[Max];
for (int i = 1; i < Max; i++)
if ((Mark[i] = Mark[i >> 1] + (i & 1)) == 6)
{
for (int k = 0; k < words.Length; k++)
if ((i & (1 << k)) != 0)
singles.Append(words[k] + " ");
singles.Replace(" ", ";", singles.Length - 2, 2);
}
return singles.ToString().Split(';');
}
static void Main(string[] args)
{
string Number = "01 02 03 04 05 06 07";
string[] singles = ToSingle(Number);
foreach (string s in singles)
Console.WriteLine(s);
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
namespace SplitStringToSingles
{
class StringToSingle
{
private int WordsLimit = 6;
private string[] words; // 从原始字符串中拆出来的单词
private Queue<string> singles = new Queue<string>(); // 重组生成的字符串的集合
// 题目要求的方法,先拆成单词,再重组,然后返回重组后的集合
public string[] ToSingle(string Number) //格式 01 02 03 04 05 06 07
{
words = Number.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length < WordsLimit)
return singles.ToArray(); // 如果单词少于6个,返回空集合
AddNextWord(0, words.Length - (WordsLimit - 1), null);
return singles.ToArray();
}
// 递归调用,完成单词重组,并存入集合
public void AddNextWord(int start, int end, string single)
{
// 如果不继续往下递归了,即 end == words.Length,生成字符串存入集合
if (end == words.Length)
for (int i = start; i < end; i++)
singles.Enqueue(single + words[i]);
// 否则迭代自己这一级所能用的单词,将其加入上一级传来的 single,并递归调用下一级
else
for (int i = start; i < end; i++)
AddNextWord(i + 1, end + 1, single + words[i] + " ");
}
}
class Program
{
static void Main(string[] args)
{
string Number = "01 02 03 04 05 06 07";
string[] singles = new StringToSingle().ToSingle(Number);
foreach (string s in singles)
Console.WriteLine(s);
Console.Read();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -