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); } }
Advertisement
Answer
There are two major things wrong with your code: First of all this line makes no sense
int indexofothers = ch[i];
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 use i
instead of ch[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:
public static void main(String []Args) { String s = "aabaab"; String c = "b"; List<Integer> list = new ArrayList<>(); char[] ch = s.toCharArray(); for(int i=0;i<ch.length;i++) { int indexofc = s.indexOf(c, i); int result = i - indexofc; if (result<=0) { result = result*(-1); } list.add(result); } System.out.println(list); }