gpt4 book ai didi

java - 查找相同字符的最长连续子序列的长度

转载 作者:行者123 更新时间:2023-11-30 08:54:47 25 4
gpt4 key购买 nike

<分区>

我试图从一个字符串中找出连续字符的最长重复子序列。

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 的新手。我刚刚编写的一些代码可能会/可能不会被使用。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com