Can someone please explain me the following program from Line 11 to Line 17.
import java.util.*;
public class Solution {
public static void main(String[] args) {
String s = "wresource";
System.out.println("Original String: "+s);
System.out.println("Index of the First unique character of the given string is at : "+first_Uniq_Char(s));
}
public static int first_Uniq_Char(String s) {
int[] freq = new int[256];
for (char c : s.toCharArray()) { //Line 11
freq[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i) - 'a'] == 1) return i;
}
return -1; //Line17
}
}
Output:
Original String: wresource
Index of the First unique character of the given string is at : 0
.
freq[] is an array which holds each element frequency ie
freq[w] =1
freq[r] =2
freq[e] =2
freq[s] =1 , etc
freq[c - 'a']++; this line converts your each character to ASCII code
As we know array index is of type integer only, we cannot have a[c] ( c is a character).
So what we have done is we have converted c into ASCII ie freq[c-'a'] means 99 - 97 = 3 ( a in ASCII is 97 and C is 99) freq[3] = 3 is same as freq[c]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.