Sadina Khatun Sadina Khatun -4 years ago 85
Java Question

How to Find Longest Distance b/w char in String

public class LongestAlphabetDistance {

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


i want to get "this is my greatest achivement in the world" distance b/w first
a = i
and last i like
t=1,h=2,i=3,s=4,
space should not count than
i=5,s=6,m=7,y=8,g=9
like that last
i
"in"
i=27
so first
i=3
last
i=27
so longest distance
b/w
24 kindly write a code for that

Answer Source
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 
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download