我试图从字符串中找到连续字符的最长重复子序列。
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 新手。我刚刚编写的一些代码可能/可能不会被使用。
最佳答案
在 boolean atBeginning = true;
之后我无法弄清楚任何事情,坦率地说,这似乎不是必需的......
你的基本逻辑应该遵循......
if character_at_current_position is equal to next_character then
currLen = currLen + 1
else if currLen is greater then maxLen then
maxLen = currLen
currLen = 1
else currLen = 1
您还需要在循环外执行另一次检查以检查 currLen 是否大于 maxLen
,以考虑最后一个字符可能做出的任何更改
更像是...
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++;
} else if (currLen > maxLen) {
maxLen = currLen;
currLen = 1;
} else {
currLen = 1;
}
}
if (currLen > maxLen) {
maxLen = currLen;
}
所以使用
System.out.println(longestRep("ccccccaaaabbbbb")); // 6 c's
System.out.println(longestRep("ccbbbaaaaddaa")); // 4 a's
System.out.println(longestRep("abcdeeefeeeeeeeefppppppp")); // 8 e's
我明白了...
6
4
8
关于java - 查找同一字符的最长连续子序列的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292117/