【发布时间】:2015-03-27 02:04:40
【问题描述】:
我正在尝试从字符串中找到最长的连续字符重复子序列。
public int longestRep(String str) {
}
当你调用方法时
longestRep("ccbbbaaaaddaa"); //Should return 4
到目前为止我使用的代码是;
public static int longestRep(String str)
{
int currLen = 1; // Current length of contiguous chars being held in str
char currLet = ' '; // Current Letter *NOT NEEDED FOR CODINGBAT
char maxLet = ' '; // Maximum length letter *NOT NEEDED FOR CODINGBAT
int maxLen = 0; // Maximum length of contiguous chars being held in str
//int maxCount = 0; // Highest count of contiguous chars being held in str
int currPos = 0; // Track where in str we are at
int strLen = str.length(); // Length of str;
for(currPos = 0; currPos < strLen -1 ; currPos++)
{
currLet = str.charAt(currPos);
//System.out.println("Curr char: "+currLet+" Next Char: "+str.charAt(currPos+1));
if(currLet == str.charAt(currPos+1))
{
currLen++;
}
if(currLen > maxLen)
{
maxLen = currLen;
//System.out.println("Max len: "+maxLen+" Curr Len: "+currLen);
//maxLet = currLet;
currLen = 1;
}
boolean atBeginning = true;
if(currPos == 0)
{
atBeginning = true;
}
else if(currPos != 0)
{
atBeginning = false;
}
if(atBeginning == false) //if not at the beginning of the string
{
if(currLet != str.charAt(currPos+1) && currLet == str.charAt(currPos-1))
{
currLen++;
}
}
if(currLen > maxLen)
{
maxLen = currLen;
currLen = 1;
}
}
return maxLen;
}
public static void main(String args[])
{
int result = longestRep("abcdeeefeeeefppppppp");
System.out.println(result);
}
但是,我收到无效的回复,并且不确定我做错了什么。 我是Java的新手。我刚刚编写的一些代码可能/可能不会被使用。
【问题讨论】:
-
请定义
"invalid responses"。 -
你可以像这样初始化 atBeginning: boolean atBeginning = (currPos == 0);或者更好的是你可以完全摆脱它并使用 if(currPos != 0) 而不是 if(atBeginning == false)
-
boolean atBeginning = true;之后的所有东西似乎都没有必要