Algorithm 最短不寻常子空间
给定两个字符串s和t,确定最短字符串z的长度,使z是s的子序列而不是t的子序列 例如: s:babab, t:babba 索尔: 3(aab) 不寻找复制可复制的代码,请如果有人可以帮助解决这个问题的直觉Algorithm 最短不寻常子空间,algorithm,dynamic-programming,Algorithm,Dynamic Programming,给定两个字符串s和t,确定最短字符串z的长度,使z是s的子序列而不是t的子序列 例如: s:babab, t:babba 索尔: 3(aab) 不寻找复制可复制的代码,请如果有人可以帮助解决这个问题的直觉 非常感谢 给你。我创建了IEnumarable方法,该方法返回所有可能的组合。这是与t。我优化了解决方案,只在不匹配字符串t上循环一次 using System; using System.Collections.Generic; namespace GuessTheNumber {
非常感谢 给你。我创建了IEnumarable方法,该方法返回所有可能的组合。这是与t。我优化了解决方案,只在不匹配字符串t上循环一次
using System;
using System.Collections.Generic;
namespace GuessTheNumber
{
public class Element:IComparable<Element>
{
public string Seq { get; set; }
public int Id { get; set; }
public int CompareTo(Element other)
{
return this.Seq.CompareTo(other.Seq);
}
}
class Program
{
static void Main(string[] args)
{
string s = "babab";
string t = "babba";
string z = ShortestUncommonSuqsequence(s, t);
}
static public string ShortestUncommonSuqsequence(string SubSequenceOf, string NotSubSequenceOf)
{
var uniqueSeq = new SortedList<Element, int>();
uniqueSeq.Add(new Element() { Seq = "", Id = -1 }, -1);
foreach (Element oneSequence in GetNextUniqueSequences(uniqueSeq, SubSequenceOf))
{
int index = oneSequence.Id + 1;
while (index < NotSubSequenceOf.Length)
{
char NotChar = NotSubSequenceOf[index];
if (oneSequence.Seq[oneSequence.Seq.Length - 1] == NotChar) break;
index++;
}
if (index == NotSubSequenceOf.Length)
{
return oneSequence.Seq;
}
else
{
oneSequence.Id = index;
}
}
return null;
}
static public IEnumerable<Element> GetNextUniqueSequences(SortedList<Element, int> UniqueSeq, string Input)
{
SortedList<Element, int> results = new SortedList<Element, int>();
foreach (var prevResult in UniqueSeq)
{
for (int i = 0; i < Input.Length; i++)
{
if (prevResult.Value < prevResult.Key.Seq.Length + i)
{
string nextStr = prevResult.Key.Seq + Input[i].ToString();
Element newElem = new Element() { Seq = nextStr, Id = prevResult.Key.Id };
if (!results.Keys.Contains(newElem))
{
results.Add(newElem, prevResult.Key.Seq.Length + i);
yield return newElem;
}
}
}
}
if (Input.Length > 1)
{
foreach (Element res in GetNextUniqueSequences(results, Input.Substring(1)))
{
yield return res;
}
}
}
}
}
使用系统;
使用System.Collections.Generic;
名称空间猜测编号
{
公共类元素:IComparable
{
公共字符串Seq{get;set;}
公共int Id{get;set;}
公共整数比较(元素其他)
{
将此顺序比较返回到(其他顺序);
}
}
班级计划
{
静态void Main(字符串[]参数)
{
字符串s=“babab”;
字符串t=“babba”;
字符串z=最短的顺序(s,t);
}
静态公共字符串ShortestUncommonSuqsequence(string SubSequenceOf,string NotSubSequenceOf)
{
var uniqueSeq=新分类列表();
添加(新元素(){Seq=”“,Id=-1},-1);
foreach(GetNextUniqueSequences中的元素oneSequence(uniqueSeq,SubSequenceOf))
{
int index=oneSequence.Id+1;
while(索引1)
{
foreach(GetNextUniqueSequences中的元素res(结果、输入、子字符串(1)))
{
收益率;
}
}
}
}
}
usa dp阵列可以解决此问题。与经典的最长公共子问题的想法相同
您是否为解决方案做出了任何努力,或者您只是想找人提供一个可复制的可复制代码?实际上并不是要寻找可复制的可复制代码,只是解决此问题的直觉或提示。我试着先想出一个递归的解决方案,但这并没有起到多大的作用!但这里的问题可能是,这个解决方案是一种蛮力解决方案,本质上也是指数型的,它返回的是最早的最短匹配。虽然它看起来像蛮力,但它是以ienumerable和jimps-pur循环的形式尽快编码的。尽可能地优化,如果你喜欢答案,请接受。