-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBob and his string
More file actions
62 lines (58 loc) · 2.15 KB
/
Bob and his string
File metadata and controls
62 lines (58 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Bob and his string
Send Feedback
King Bob is in playful mood today. He started playing with string S. As he was playing, a weird question came in his mind. He wondered what is the maximum number of characters, between any two same characters in the string. He needs your help in solving this question. Can you help him solve this question?
Note: String S is composed of lowercase letters of the Latin alphabet. If there are no two same characters in the string, print -1.
Input Format:
The first line of input contains one integer T, denoting the number of test cases.
Each of the next T line contains one string S.
Constraints:
1 < T < 10
1 < |S| < 100000, where S determines the length of the string.
String is composed of lowercase alphabets ranging from a to z.
Time limit : 1 sec
Output Format:
For each test case, output the maximum number of characters between any two same characters in the string. If there are no two same characters in the string, print -1.
Print answer for each test case in a new line.
Sample Input 1:
2
aba
babcddc
Sample Output 1:
1
2
Explanation:
1) For string = aba
There is only one character between 2 occurrences of a.
2) For string = babcddc
There is one character between 2 occurrences of b, and 2 characters between 2 occurrences of c. So the answer is 2.
code in java ********************************************
import java.util.Scanner;
public class Main {
public static int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i =0;i<n;i++)
{
String str = sc.next();
System.out.println(solve(str));
}
}
public static int solve(String str)
{
int n = str.length();
int res = -1;
int []firstInd = new int[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++)
firstInd[i] = -1;
for (int i = 0; i < n; i++)
{
int first_ind = firstInd[str.charAt(i)];
if (first_ind == -1)
firstInd[str.charAt(i)] = i;
else
res = Math.max(res, Math.abs(i - first_ind - 1));
}
return res;
}
}