Mr. Binary geeks solution
Problem:
string s containing lower case English alphabets. He can only jump to some other location j (j>i) only if s[j] = s[i]+1. He wants to find out the maximum distance he can reach, i.e., maximum index of the string he can reach.
Example :
aaabbcdbdt - 8
aabcb - 4
Approach 1:
Use Recursion and check with every digit
If next character is +1 or if next character is a than previous then change value of maxIndex
Approach 2:
Loop through the string , check if the character is already visited or is 1 greater than previous then modify.
Code:
public static int longestCons(String str)
{
char cur='a';
int max=0;
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)<=cur+1)
{
max=Math.max(max,i);
if(str.charAt(i)==cur+1)
cur++;
}
}
return max;
}
string s containing lower case English alphabets. He can only jump to some other location j (j>i) only if s[j] = s[i]+1. He wants to find out the maximum distance he can reach, i.e., maximum index of the string he can reach.
Example :
aaabbcdbdt - 8
aabcb - 4
Approach 1:
Use Recursion and check with every digit
If next character is +1 or if next character is a than previous then change value of maxIndex
Approach 2:
Loop through the string , check if the character is already visited or is 1 greater than previous then modify.
Code:
public static int longestCons(String str)
{
char cur='a';
int max=0;
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)<=cur+1)
{
max=Math.max(max,i);
if(str.charAt(i)==cur+1)
cur++;
}
}
return max;
}
0 Comments:
Post a Comment