You are on page 1of 18

STRINGS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
  Weights substring

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
  Weightes substring
Concept:
Given a string P consisting of small English letters and a string Q consisting of weight
of all characters of English alphabet such that for all ‘i’, 0 ≤ Q[i] ≤ 9. The task is to find
the total numbers of unique substring with sum of weights atmost K.
Examples:
Input: P = “ababab”, Q = “12345678912345678912345678”, K = 5 
Output: 7 
Explanation: 
The substrings with the sum of weights of individual characters ≤ 5 are: 
“a”, “ab”, “b”, “bc”, “c”, “d”, “e”
Input: P = “acbacbacaa”, Q = “12300045600078900012345000”, K = 2 
Output: 3 
Explanation: 
The substrings with the sum of weights of individual characters ≤ 2 are: 
“a”, “b”, “aa”  © 2016 SMART
SMART TRAINING RESOURCES Training
INDIA PVT. Resources
LTD. Pvt. Ltd. © 2018 SMART Training Resources Pvt. Ltd.
Example:1
             // Add weight to current sum
// Java program to find the count of
            sum += Q.charAt(pos) - '0';
// all the sub-Strings with weight of
  
// characters atmost K
            // Add current character to subString
import java.util.*;
            s += P.charAt(j);  
 
            // If sum of characters is <=K
class GFG{
            // then insert  into the set
  
            if (sum <= K) {
// Function to find the count of
                S.add(s);
// all the subStrings with weight
            }
// of characters atmost K
  
static int distinctSubString(String P, String Q,
            else {
                      int K, int N)
                break;
{
            }
  
        }
    // Hashmap to store all subStrings
    }  
    HashSet<String> S = new HashSet<String>();  
    // Finding the size of the set
    // Iterate over all subStrings
    return S.size();
    for (int i = 0; i < N; ++i) {  
}  
        // Maintain the sum of all characters
// Driver code
        // encountered so far
public static void main(String[] args)
        int sum = 0;
{
// Maintain the subString till the
    String P = "abcde";
        // current position
    String Q = "12345678912345678912345678";
        String s = "";  
    int K = 5;
        for (int j = i; j < N; ++j) {  
    int N = P.length();  
            // Get the position of the
    System.out.print(distinctSubString(P, Q, K, N));
            // character in String Q
}
            int pos = P.charAt(j) - 'a';
}

Output: 7
 

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:2
// Java implementation of the approach // Driver code
import java.util.HashMap;     public static void main(String []args)
import java.util.Map;      {
class GfG         String str[] = { "geeksforgeeks",
{// Function to return the required string "algorithms",
score                                           
    static int strScore(String str[], String   "stack" };
s, int n)         String s = "algorithms";
    {         int n = str.length;
        // create a hash map of strings in         System.out.println(strScore(str,
str s, n));
 HashMap<String, Integer> m = new          
HashMap<>();          }
        // Store every string in the map }
  // along with its position in the array Output:244
        for (int i = 0; i < n; i++)
            m.put(str[i], i + 1);     
// If given string is not present in str[]
        if (!m.containsKey(s))
            return 0;     
        int score = 0;     
        for (int i = 0; i < s.length(); i++)
            score += s.charAt(i) - 'a' +
1;     
 // Multiply sum of alphabets with position
        score = score * m.get(s);     
        return score;
    }
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Move hyphen to beginning

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Move hyphen to beginning
Definition:
Given a string that has set of words and spaces, write a program to move all spaces to front
of string, by traversing the string only once.

Examples: 
Input : str = "geeks for geeks"
Output : ste = " geeksforgeeks"
 
Input : str = "move these spaces to beginning"
Output : str = " movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:1(Using Swap)

    public static void main(String[] args){


        char str[] = "Hey there, it's
class Main{ GeeksforGeeks".toCharArray();
          moveSpaceInFront(str);
    static void moveSpaceInFront(char str[]){         System.out.println(String.valueOf(str));
    }
        int i = str.length-1; }
        for (int j = i; j >= 0; j--) Output: 
            if (str[j] != ' '){ Heythere,it'sGeeksforGeeks
                char c = str[i];
                str[i] = str[j];  
                str[j] = c;
                i--;
            }
    }
 

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Example:2(Without using swap)

public static void main(String[] args){


class GFG{
static void     char str[] = "Hey there, it's
GeeksforGeeks".toCharArray();
moveSpaceInFront(char     moveSpaceInFront(str);
str[]){     System.out.println(String.valueOf(str));

int i = str.length-1; }
}

 Output:
for (int j = i; j >= 0; j--)
if (str[j] != ' ') Heythere,it'sGeeksforGeeks

str[i--] = str[j];
     while (i >= 0)
        str[i--] = ' ';
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm

What is Manacher's algorithm?

• Manacher's algorithm is used to find the longest palindromic


substring in any given string. This algorithm is faster than the brute
force approach, as it exploits the idea of a palindrome happening
inside another palindrome.
• Manacher's algorithm is designed to find the palindromic substrings
with odd lengths only. To use it for even lengths also, we tweak the
input string by inserting the character "#" at the beginning and each
alternate position after that (changing "abcaac" to
"#a#b#c#a#a#c#").
• In the case of an odd length palindrome, the middle character will
be a character of the original string, surrounded by "#".
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Steps of the Manacher's Algorithm

Steps of the Manacher's algorithm are as follows:

1. Create an array or a list (sCharssChars) of length strLenstrLen which is 2 * n +


32∗n+3 (nn being the length of the given string), to modify the given string.
2. Assign the first and last element of sCharssChars to be "@" and "$", respectively.
3. Fill the blank spaces in sCharssChars by characters of the given string and "#" alternatively.
4. Declare variables
1. Implicating maximum detected length of palindrome substring maxLen = 0maxLen=0
2. Position from where to start searching start = 0start=0
3. Highest position of the extreme right character of all detected palindromes maxRight =
0maxRight=0
4. Center of the detected palindrome center = 0center=0.
5. Create an array or a list pp to record the width of each palindrome about their center, center
being the corresponding characters in sCharssChars.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Steps of the Manacher's Algorithm

7.Create a for loop iterating from 11 to strLen - 1strLen−1, with ii incrementing in each iteration.


8.In each iteration, check if i < maxRighti<maxRight, if yes, then assign minimum of maxRight
- imaxRight−i and p[2 * center - i]p[2∗center−i] to p[i]p[i].
9.Nest a while loop inside the for loop, to count with width along the center, condition
being, sChars[i + p[i] + 1]sChars[i+p[i]+1] is equal to sChars[i - p[i] - 1]sChars[i−p[i]−1], if yes,
increment p[i]p[i] by 1.
10.To update center, check if i + p[i]i+p[i] is greater than maxRightmaxRight, if yes,
assign centercenter to be 11, and maxRightmaxRight to be i + p[i]i+p[i].
11.For updating the Maximum length detected, check if p[i]p[i] is greater than maxLenmaxLen,
if yes, then assign startstart to be (i - p[i] - 1) / 2(i−p[i]−1)/2, and maxLenmaxLen to be p[i]p[i].
12.Come out of the for loop, and print the substring in the given string, starting
from startstart and ending at start + maxLen - 1start+maxLen−1.

© 2016 SMART
SMART TRAINING RESOURCES Training
INDIA PVT. Resources
LTD. Pvt. Ltd. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm-Example

// Java program to implement Manacher's Algorithm


import java.util.*; // get currentLeftPosition iMirror
  // for currentRightPosition i
class GFG iMirror = 2 * C - i;
{
L[i] = 0;
    static void findLongestPalindromicString(String text)
    { diff = R - i;
        int N = text.length();
        if (N == 0) // If currentRightPosition i is within
            return; // centerRightPosition R
        N = 2 * N + 1; // Position count if (diff > 0)
        int[] L = new int[N + 1]; // LPS Length Array L[i] = Math.min(L[iMirror], diff);
        L[0] = 0;
        L[1] = 1;
// Attempt to expand palindrome centered at
        int C = 1; // centerPosition
// currentRightPosition i. Here for odd positions,
        int R = 2; // centerRightPosition
        int i = 0; // currentRightPosition // we compare characters and if match then
        int iMirror; // currentLeftPosition // increment LPS Length by ONE. If even
        int maxLPSLength = 0; position,
        int maxLPSCenterPosition = 0; // we just increment LPS by ONE without
        int start = -1; // any character comparison
        int end = -1; while (((i + L[i]) + 1 < N && (i - L[i]) > 0) &&
        int diff = -1;  (((i + L[i] + 1) % 2 == 0) ||
        // Uncomment it to print LPS Length array (text.charAt((i + L[i] + 1) / 2) ==
        // printf("%d %d ", L[0], L[1]);
text.charAt((i - L[i] - 1) / 2))))
        for (i = 2; i < N; i++)
        { {
  L[i]++;
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm-Example
if (L[i] > maxLPSLength) // Track maxLPSLength     String text = "babcbabcbaccba";
{
findLongestPalindromicString(text);
maxLPSLength = L[i];
maxLPSCenterPosition = i;
text = "abaaba";
} findLongestPalindromicString(text);
text = "abababa";
// If palindrome centered at currentRightPosition i findLongestPalindromicString(text);
// expand beyond centerRightPosition R,
text = "abcbabcbabcba";
// adjust centerPosition C based on expanded palindrome.
if (i + L[i] > R) findLongestPalindromicString(text);
{ text = "forgeeksskeegfor";
C = i; findLongestPalindromicString(text);
R = i + L[i];
text = "caba";
}
findLongestPalindromicString(text);
// Uncomment it to print LPS Length array
// printf("%d ", L[i]); text = "abacdfgdcaba";
} findLongestPalindromicString(text);

start = (maxLPSCenterPosition - maxLPSLength) / 2;


end = start + maxLPSLength - 1; text = "abacdfgdcabba";
System.out.printf("LPS of string is %s : ", text); findLongestPalindromicString(text);
for (i = start; i <= end; i++)
System.out.print(text.charAt(i)); text = "abacdedcaba";
System.out.println();
}
findLongestPalindromicString(text);
}
// Driver Code }
public static void main(String[] args)  
{

        

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm-Example
       

Output:

LPS of string is babcbabcbaccba : abcbabcba


LPS of string is abaaba : abaaba
LPS of string is abababa : abababa
LPS of string is abcbabcbabcba :
abcbabcbabcba
LPS of string is forgeeksskeegfor : geeksskeeg
LPS of string is caba : aba
LPS of string is abacdfgdcaba : aba
LPS of string is abacdfgdcabba : abba
LPS of string is abacdedcaba : abacdedcaba
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Manacher's Algorithm-Example
if (L[i] > maxLPSLength) // Track public static void main(String[] args){
maxLPSLength{     String text = "babcbabcbaccba";
maxLPSLength = L[i];
findLongestPalindromicString(text);
maxLPSCenterPosition = i;
text = "abacdedcaba";
}
findLongestPalindromicString(text);
if (i + L[i] > R){ }
C = i; }
R = i + L[i];  
}
}

start = (maxLPSCenterPosition -
maxLPSLength) / 2;
end = start + maxLPSLength - 1;
System.out.printf("LPS of string is %s : ",
text);
for (i = start; i <= end; i++)
System.out.print(text.charAt(i));
System.out.println();
}

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Thank you…

© 2016 SMART
SMART TRAINING RESOURCES Training
INDIA PVT. Resources
LTD. Pvt. Ltd. © 2018 SMART Training Resources Pvt. Ltd.

You might also like