3 回答
TA贡献1993条经验 获得超5个赞
这对我有用:
public static int solution(string S)
{
return
S
.Split("1234567890".ToCharArray()) // split on invalid characters
.Where(x => x.Any(y => char.IsUpper(y))) // keep only those portions containing an uppercase char
.Select(x => x.Length) // get the length of each string
.Max(); // find the longest
}
这是基于问题中的代码的解决方案:
public static int solution(string S)
{
int result = 0;
int tally = 0;
bool foundUpper = false;
for (int i = 0; i < S.Length; i++)
{
char Z = S[i];
if (char.IsDigit(Z))
{
if (foundUpper && tally > result)
{
result = tally;
}
tally = 0;
foundUpper = false;
}
else
{
tally++;
foundUpper |= char.IsUpper(Z);
}
}
if (foundUpper && tally > result)
{
result = tally;
}
return result;
}
还有第三种选择:
public static int solution3(string S)
{
return S.ToCharArray().Concat(new [] { '0' }).Aggregate(
new { result = 0, tally = 0, foundUpper = false },
(a, x) => char.IsDigit(x)
? new { result = (a.foundUpper && a.tally > a.result) ? a.tally : a.result, tally = 0, foundUpper = false }
: new { result = a.result, tally = a.tally + 1, foundUpper = a.foundUpper || char.IsUpper(x) })
.result;
}
TA贡献1936条经验 获得超6个赞
代码和你写的完全不同。您正在寻找非数字的子字符串,然后在这些子字符串的末尾,您必须检查子字符串的至少一个字符是否为大写。如果是,那么这个子串可能是一个候选,然后必须考虑它的长度。检查是否存在大写字符是通过upperCaseFound布尔变量完成的。
public static int LongestSubstring(string s)
{
int maxLength = 0;
bool upperCaseFound = false;
int length = 0;
foreach (char ch in s)
{
if (char.IsDigit(ch))
{
if (upperCaseFound && length > maxLength)
{
maxLength = length;
}
upperCaseFound = false;
length = 0;
continue;
}
if (char.IsUpper(ch))
{
upperCaseFound = true;
}
length++;
}
if (upperCaseFound && length > maxLength)
{
maxLength = length;
}
return maxLength;
}
TA贡献1803条经验 获得超6个赞
public static int solution(string s)
{
int result = 0;
for (int i = 0; i < s.Length; i++)
{
bool containsUpper = false;
if (Char.IsLetter(s[i]))
{
int len = 0;
do
{
if (Char.IsUpper(s[i])){
containsUpper = true;
}
i++;
len++;
} while (i<s.Length&&Char.IsLetter(s[i])) ;
if( (len > result )&&containsUpper)
result = len;
}
}
return result;
}
- 3 回答
- 0 关注
- 197 浏览
添加回答
举报