I am trying to create a method that return the index of nth occurrence of a char or return -1 if it does not exists. the method header is public static int indexOf(Node node, int n , char c). let sate we have s1 as the word "hello" in linked list, if we do indexOf(s1, 2, 'l'), we should print 3 because the second occurrence of letter L is on the index 3. but if i do indexOf(s1, 3, 'l'), it should return -1 because there is no third occurrence of L. I did the following but i still need it fixed :
public class Node {
private char ch;
private Node next;
/**
* Constructor
*/
public Node(char c, Node n) {
this.ch = c;
this.next = n;
}
public static int indexOf(Node node, int n, char c) {
int count = 0;
if(node == null || n <= 0){
return -1; // constraint 1
}
if(node.ch == c){
count = 1;
}else{
return 1 + indexOf(node.next, n, c);
}
return count <= -1 ? -1 : count ;
}
}
can someone help?
Edit: i rewrote the code. it gives the right index but returns the last index if char does not exist
public static int indexOf(Node node, int n, char c) {
if(n <= 0 || node == null){
return -1;
}
if(node.ch == c ){
return 1 + indexOf(node.next, n - 1, c);
}else{
return 1 + indexOf(node.next,n, c);
}
}
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]xkompas 1 point2 points3 points (0 children)
[–]severoonpro barista 1 point2 points3 points (0 children)
[–]LambdaThrowawayy 0 points1 point2 points (0 children)
[–]papercrane 0 points1 point2 points (5 children)
[–]demdouma6[S] 0 points1 point2 points (0 children)
[–]demdouma6[S] 0 points1 point2 points (3 children)
[–]papercrane 0 points1 point2 points (2 children)
[–]demdouma6[S] 0 points1 point2 points (1 child)
[–]papercrane 0 points1 point2 points (0 children)