gpt4 book ai didi

java - 如何查找字符串中字符之间的最长距离

转载 作者:行者123 更新时间:2023-12-02 02:49:08 25 4
gpt4 key购买 nike

public class LongestAlphabetDistance {

public int longDistance(String str, String a) {
str = "this is my greatest achievement in the world";
a = "i";
int count =0;
// code logic for longest difference
return count;
}
}

我想首先获得“这是我在世界上最伟大的成就”距离黑白a = i 和最后一个 i t=1,h=2,i=3,s=4, 空间不应比 i=5,s =6,m=7,y=8,g=9 就像最后一个i“in”i=27所以首先i=3 最后一个i=27 所以最长的距离b/w 24 请为此编写一个代码

最佳答案

public class LongestAlphabetDistance {

public int longDistance(String str, String a) {
str = "this is my greatest achivement in the world";
a = "i";
str = str.replaceAll("\\s", "");
char[] chArray = str.toCharArray();
ArrayList<Integer> inArray = new ArrayList<>();

for(int i =0;i<chArray.length;i++) {
if(chArray[i] == a.charAt(0) ) {
inArray.add(i+1);
}
}

return inArray.get(inArray.size()-1)-inArray.get(0); // 24
}
}

关于java - 如何查找字符串中字符之间的最长距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095075/

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