3 回答

TA貢獻1993條經驗 獲得超6個贊
這對我有用:
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條經驗 獲得超7個贊
代碼和你寫的完全不同。您正在尋找非數字的子字符串,然后在這些子字符串的末尾,您必須檢查子字符串的至少一個字符是否為大寫。如果是,那么這個子串可能是一個候選,然后必須考慮它的長度。檢查是否存在大寫字符是通過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 關注
- 223 瀏覽
添加回答
舉報