求字符串中两个字符的距离并将其输入数组的方法
试图为学校解决这个问题
“给定一个字符串 s 和一个字符 c,返回一个与 s 长度相同的新整数列表,其中对于每个索引 i,其值设置为 s[i] 到 c 的最近距离。您可以假设 c 存在于 s 中。”
例如
输入 s =“aabaab” c =“b”
输出 [2, 1, 0, 1, 1, 0]
我的输出 [63,63,64,63,63]
我不知道我做错了什么,我该怎么办?
public static void main(String []Args) {
String s = "aabaab";
String c = "b";
List<Integer> list = new ArrayList<Integer>();
char[] ch = s.toCharArray();
int indexofc = new String(ch).indexOf(c);
for(int i=0;i<ch.length;i++) {
int indexofothers = ch[i];
int result = indexofothers - indexofc;
if (result<=0) {
result = result*(-1);
}
list.add(result);
}
System.out.println(list);
}
}
trying to solve this question for school
"Given a string s and a character c, return a new list of integers of the same length as s where for each index i its value is set the closest distance of s[i] to c. You can assume c exists in s."
for example
Input
s = "aabaab"
c = "b"
Output
[2, 1, 0, 1, 1, 0]
My Output
[63,63,64,63,63]
I can't figure out what im doing wrong, how should I go about it?
public static void main(String []Args) {
String s = "aabaab";
String c = "b";
List<Integer> list = new ArrayList<Integer>();
char[] ch = s.toCharArray();
int indexofc = new String(ch).indexOf(c);
for(int i=0;i<ch.length;i++) {
int indexofothers = ch[i];
int result = indexofothers - indexofc;
if (result<=0) {
result = result*(-1);
}
list.add(result);
}
System.out.println(list);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码有两个主要问题:
首先,这一行没有意义。
您正在尝试获取索引,但取的是位置
i
处的字符,然后将其转换为整数,结果可能类似于 63。因此,使用i
而不是ch[i]
。其次,如果您像这样使用它,则 indexOf 方法将仅返回第一个索引。添加当前索引(并将其移动到循环中),否则您将始终获得到第一个 b 的距离。所以你的代码可能如下所示:
There are two major things wrong with your code:
First of all this line makes no sense
You are trying to get an index but are instead taking the character at the position
i
which will then be converted to an integer which can result is something like 63. So usei
instead ofch[i]
.Second the indexOf method wil only return the first index if you use it like thaat. Add the current index (and move it into the loop) or otherwise you will always get the distance to the first b. So your code could look like this: