[英]Algorithm Palindrome C#
Can anyone please help, what am I missing on my code?任何人都可以帮忙,我的代码中缺少什么? The part one is Calculate The Palindrome Level, my answers all correct, I just could not figure it out for the part two ie Sum of The Palindrome Level, I could not meet the answer
第一部分是计算回文级别,我的答案全部正确,我只是想不出第二部分即回文级别的总和,我无法满足答案
Palindrome Palindrome is a word, phrase, or sequence that reads the same backward as forward eg "madam", "nurses run", "23499432".
回文 回文是一个单词、短语或序列,其向后读与向前读相同,例如“女士”、“护士跑”、“23499432”。 When palindrome sequence is splited in half, the first sequence may be a palindrome too.
当回文序列一分为二时,第一个序列也可能是一个回文序列。
Part #1第1部分
"Palindrome Level" is how many times a palindrome sequence can be splited in half until the first sequence from splited is not a palindrome or until the first sequence is just a character.
“回文级别”是指一个回文序列可以被分成两半的次数,直到分裂的第一个序列不是回文或直到第一个序列只是一个字符。 Palindrome level ignores space and case insensitive (if the sequence length is odd number, then after split the sequence, take the middle character to the first sequence: "madam" -> "mad")
回文层忽略空格且不区分大小写(如果序列长度为奇数,则将序列拆分后,取中间字符到第一个序列:“madam”->“mad”)
For example:例如:
-nurses run: nursesrun -> nurse (1 level)
-nurses run:nursesrun -> 护士(1 级)
-451545154: 451545154 -> 45154 -> 451 (2 level)
-451545154: 451545154 -> 45154 -> 451 (2 级)
-dam madam mad: dammadammad -> dammad -> dam (2 level)
-dam maddam mad: dammadammad -> dammad -> dam (2 level)
Part #2第2部分
Defined string's prefixes as all prefixes of a string nun in inun : n, nu, nun, nunin, nunini, nuninin, nunininu, nunininun
将字符串的前缀定义为 inun 中字符串 nun 的所有前缀:n, nu, nun, nunin, nunini, nuninin, nunininu, nunininun
"Sum of the palindrome level" of all string's prefixes is calculated by add all palindrome level of all prefixes of a string.
所有字符串前缀的“回文级别总和”是通过将一个字符串的所有前缀的所有回文级别相加来计算的。
For example :例如 :
abacaba : a(0), ab(0), aba(1), abac(0), abaca(0), abacab(0), abacaba(1) =>sum of the palindrome level :2
abacaba : a(0), ab(0), aba(1), abac(0), abaca(0), abacab(0), abacaba(1) => 回文级别的总和:2
Below is my code下面是我的代码
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Calculate Palindrome level");
foreach (var test in _CreatePalindromeLevelTestWords())
{
_CheckAnswer(test.Key, test.Value, CalculatePalindromeLevel(test.Key));
}
Console.WriteLine("Sum of the palindrome level");
//Your code goes here
foreach (var test in _CreateSumOfPalindromeLevelTestWords())
{
_CheckAnswer(test.Key, test.Value, SumOfPalindromeLevel(test.Key));
}
Console.ReadKey();
}
public static int CalculatePalindromeLevel(string word)
{
string strRemovedSpaces = StringRemoveSpace(word).ToLower();
string nextstr = strRemovedSpaces;
int count = 0;
bool palResult = isPal(nextstr);
while(palResult)
{
count++;
int strLength;
if (nextstr.Length % 2 == 0)
{
strLength = Convert.ToInt32(Math.Floor((decimal)nextstr.Length / 2));
}
else
{
strLength = Convert.ToInt32(Math.Ceiling((decimal) nextstr.Length / 2));
}
nextstr = nextstr.Substring(0, strLength);
palResult = isPal(nextstr);
}
return count;
}
public static int SumOfPalindromeLevel(string word)
{
string strRemovedSpace = StringRemoveSpace(word).ToLower();
string nextstr = "";
int count = 0;
for (int i = 1; i < strRemovedSpace.Length; i++)
{
nextstr = strRemovedSpace.Substring(0, i);
var palResult = isPal(nextstr);
if (palResult == true)
{
count++;
}
}
return count;
}
public static string StringRemoveSpace(string w)
{
string str = string.Join("", w.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
return str;
}
public static bool isPal(string s)
{
int length = s.Length;
for (int i = 0; i < length / 2; i++)
{
if (s[i] != s[length - i - 1])
return false;
}
return true;
}
public static Dictionary<string,int> _CreatePalindromeLevelTestWords()
{
return new Dictionary<string, int>
{
{"nurses run",1 },
{"dam madam mad",2 },
{"Sitis sit is s it is sitis",3 }
};
}
public static Dictionary<string, int> _CreateSumOfPalindromeLevelTestWords()
{
return new Dictionary<string, int>
{
{"nurses run",1 },
{"dam madam mad",3},
{"Sitis sit is s it is sitis",7}
};
}
public static void _CheckAnswer(string question, int expected, int answer)
{
Console.WriteLine(answer.Equals(expected) ? $"{question}:{answer} (Right)" : $"{question}:{answer}(Wrong: expected {expected})");
}
}
I'm struggling with the Part #2, it didn't match with the expected result.我正在为第 2 部分苦苦挣扎,它与预期的结果不符。 Could you please help, what am I missing with?
你能帮忙吗,我错过了什么? My result for the dammadammad->2 and sitissitissitissitis->4, while it should meet 3 and 7 respectively.
我对 dammadammad->2 和 sitissitissitissitis->4 的结果,而它应该分别满足 3 和 7。 I don't think there's a relation among the part #1 and the part #2, but I include the part one, in case it does.
我认为第 1 部分和第 2 部分之间没有关系,但我将第 1 部分包括在内,以防万一。 I can not sleep :( and want to know the answer, I'm still trying to find it.
我睡不着:(想知道答案,我仍在努力寻找。
There are two issues.有两个问题。
To prove this, modify your method to print out some debug information to the console, to match the example that is given: https://dotnetfiddle.net/dfOh30为了证明这一点,请修改您的方法以将一些调试信息打印到控制台,以匹配给出的示例: https : //dotnetfiddle.net/dfOh30
int SumOfPalindromeLevel(string word)
{
string strRemovedSpace = StringRemoveSpace(word).ToLower();
string nextstr = "";
int count =0;
Console.Write("{0} => ", word);
for(int i=1;i<strRemovedSpace.Length;i++)
{
nextstr = strRemovedSpace.Substring(0,i);
var palResult = isPal(nextstr);
Console.Write("{0}({1}) ", nextstr, palResult ? 1 : 0);
if(palResult==true){
count++;
}
}
Console.WriteLine();
Console.WriteLine("=> sum of palindrome level: {0}", count);
return count;
}
When you run this: SumOfPalindromeLevel("abacaba");
当你运行这个:
SumOfPalindromeLevel("abacaba");
you will get the following output:您将获得以下输出:
abacaba => a(1) ab(0) aba(1) abac(0) abaca(0) abacab(0)
=> sum of palindrome level: 2
Even though the resulting value of 2 was expected, notice how the 'a' on its own is counted and the final character is not evaluated.即使结果值 2 是预期的,请注意 'a' 本身是如何计算的,并且不评估最终字符。 We call this boundary conditions , you've managed to fail both boundaries ;)
我们称之为边界条件,您已经设法使两个边界都失败了 ;)
This is the first place to check when you sometimes get the right answer but not always, this is a very common pitfall with these types of questions.这是您有时会得到正确答案的第一个检查位置,但并非总是如此,这是此类问题的一个非常常见的陷阱。
This was the expected output:这是预期的输出:
abacaba => a(0) ab(0) aba(1) abac(0) abaca(0) abacaba(1)
=> sum of palindrome level: 2
So there are two changes to make:所以有两个改变:
bool isPal(string s)
{
int length = s.Length;
if (length > 1)
{
for (int i = 0; i < length / 2; i++)
{
if (s[i] != s[length - i - 1])
return false;
}
return true;
}
return false;
}
Then in your SumOfPalindromeLevel
method you need to iterate all the characters:然后在您的
SumOfPalindromeLevel
方法中,您需要迭代所有字符:
Change this:改变这个:
for(int i=1; i<strRemovedSpace.Length; i++)
to:到:
for(int i=1; i<=strRemovedSpace.Length; i++)
But this is still only half of the equation.但这仍然只是等式的一半。 This still doesn't satisfy the requirement for
dam madam mad
.这还是达不到
dam madam mad
的要求。
If we take the hint:如果我们接受提示:
when palindrome sequence is splitted in half, this first sequence may be a palindrome too
当回文序列被分成两半时,第一个序列也可能是回文
And we include the sum of the halfs of the strings in the result then we can get the score of 3 for dammadammad
:我们将字符串的一半之和包含在结果中,然后我们可以得到
dammadammad
的分数 3:
int SumOfPalindromeLevel(string word)
{
string strRemovedSpace = StringRemoveSpace(word).ToLower();
string nextstr = "";
int count =0;
Console.Write("{0} => ", word);
for(int i=1;i<=strRemovedSpace.Length;i++)
{
nextstr = strRemovedSpace.Substring(0,i);
var palResult = isPal(nextstr);
Console.Write("{0}({1}) ", nextstr, palResult ? 1 : 0);
if(palResult==true){
count++;
}
}
Console.WriteLine();
while (strRemovedSpace.Length > 1)
{
strRemovedSpace = strRemovedSpace.Substring(0,(int)Math.Ceiling((double)strRemovedSpace.Length/2d));
var palResult = isPal(strRemovedSpace);
Console.Write("{0}({1}) ", strRemovedSpace, palResult ? 1 : 0);
if(palResult==true){
count++;
}
Console.WriteLine();
}
Console.WriteLine(word + " => sum of palindrome level: {0}", count);
Console.WriteLine();
return count;
}
Which returns score of 3
for dam madam mad
:其中
dam madam mad
返回3
分:
dammadammad => d(0) da(0) dam(0) damm(0) damma(0) dammad(1) dammada(0) dammadam(0) dammadamm(0) dammadamma(0) dammadammad(1)
dammad(1)
dam(0)
da(0)
d(0)
dammadammad => sum of palindrome level: 3
But it still does not return 7 for Sitis sit is s it is sitis
:但它仍然没有返回 7 for
Sitis sit is s it is sitis
:
Sitis sit is s it is sitis => s(0) si(0) sit(0) siti(0) sitis(1) sitiss(0) sitissi(0) sitissit(0) sitissiti(0) sitissitis(1) sitissitiss(0) sitissitissi(0) sitissitissit(0) sitissitissiti(0) sitissitissitis(1) sitissitissitiss(0) sitissitissitissi(0) sitissitissitissit(0) sitissitissitissiti(0) sitissitissitissitis(1)
sitissitis(1)
sitis(1)
sit(0)
si(0)
s(0)
Sitis sit is s it is sitis => sum of palindrome level: 6
So that's me out, I'd love to study the original requirement in full, rather than through images, perhaps you can paste the actual text in?
所以这就是我,我很想完整地研究原始要求,而不是通过图像,也许您可以将实际文本粘贴进去?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.