others - C# - 我的int'LastTwoChars'返回"StartIndex cannot be less than zero."异常


static void Main(string[] args)


{


 try


 {


 // Sample data - inputs 3 ints.


 Console.WriteLine(Solution1(6, 1, 1));


 Console.WriteLine(Solution1(1, 3, 1));


 Console.WriteLine(Solution1(0, 1, 8));


 Console.WriteLine(Solution1(5, 2, 4));


 }


 catch (Exception e)


 {


 Console.WriteLine(e.Message);


 }



}



static string Solution1(int A, int B, int C)


{



 string a ="a"; // a/b/c are added to string diverse when needed.


 string b ="b";


 string c ="c";


 string diverse ="";


 int totalLength = A + B + C; // Length of all 3 arrays



 for(int i = 1; i <= totalLength; i++) 


 {


 if (A >= B && A >= C && A > 0) { diverse = diverse + a; A = A - 1; }


 if (B >= A && B >= C && B > 0) { diverse = diverse + b; B = B - 1; }


 if (C >= A && C >= B && C > 0) { diverse = diverse + c; C = C - 1; }


 }


 return diverse;


}



下面是这个附加检查的代码,我需要它能工作。


static string Solution1(int A, int B, int C)


{


 string a ="a"; // a/b/c are added to string diverse when needed.


 string b ="b";


 string c ="c";


 string diverse ="";


 int totalLength = A + B + C; // Length of all 3 arrays



 for (int i = 1; i <= totalLength; i++)


 {


 // Finds the last 2 characters in the diverse string.


 int LastTwoChars = diverse.Length - 2;


 string twoCharCheck = diverse.Substring(LastTwoChars, 2);



 if (A > 0 && B < 2 && C < 2 && twoCharCheck !="aa")


 {


 diverse = diverse + a; A = A - 1;


 }


 if (B > 0 && A < 2 && C < 2 && twoCharCheck !="bb")


 {


 diverse = diverse + b; B = B - 1;


 }


 if (C > 0 && B < 2 && A < 2 && twoCharCheck !="cc")


 {


 diverse = diverse + c; C = C - 1;


 }



 }


 return diverse;


}



时间:

你必须至少有2个字符后,才能进行字符串检查:


int LastTwoChars = diverse.Length - 2;


string twoCharCheck = LastTwoChars >= 0 ? diverse.Substring(LastTwoChars, 2) : string.Empty; // identical with if (LastTwoChars >= 0) twoCharCheck = diverse.Substring(LastTwoChars, 2); else twoCharCheck = string.Empty



if (A > 0 && B < 2 && C < 2 && (LastTwoChars < 0 || twoCharCheck !="aa")) // check the end only if you have at least 2 chars;


{


...


}


....



你可以看到代码变得非常快,所以我会使用helper方法:


// returns the last two chars in a string format, or a default user string


private static string LastTwoCharsOrDefault(string input, string default)


{


 var lastTwoCharsIdx = input.Length - 2;


 if (lastTwoCharsIdx > 0 )


 {


 return input.Substring(lastTwoCharsIdx, 2);


 }


 // we don't have at least 2 chars, so lets just return the default


 return default;


}



然后,你可以像这样更改代码:





if (A > 0 && B < 2 && C < 2 && string.Equals("aa", LastTwoCharsOrDefault(diverse,"aa"), StringComparison.OrdinalIgnoreCase))


...



string diverse ="";

然后执行 string twoCharCheck = diverse.Substring(LastTwoChars, 2);


LastTwoChars is going to be -2 the first time through the loop.



...