0% found this document useful (0 votes)
18 views12 pages

Data Structures For Placement Training (Strings) - 18.10.2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views12 pages

Data Structures For Placement Training (Strings) - 18.10.2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

STRINGS:

PROGRAMS:
Permutations of a given string
Longest Palindrome in a String
Recursively remove all adjacent duplicates
Check if string is rotated by two places
Longest Distinct Characters in the string
Longest Common Prefix

ASSIGNMENT:
Anagram
Reverse words in a given string
Remove Duplicates
Roman Number to Integer
Permutations of given String
Given a string S, the task is to write a program to print all permutations of a given string.
A permutation also called an “arrangement number” or “order,” is a rearrangement of the
elements of an ordered list S into a one-to-one correspondence with S itself. A string of length N
has N! permutations.
Examples:
Input: S = “ABC”
Output: “ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”
Input: S = “XY”
Output: “XY”, “YX”

Follow the given steps to solve the problem:


 Create a function permute() with parameters as input string, starting index of the string,
ending index of the string
 Call this function with values input string, 0, size of string – 1
o In this function, if the value of L and R is the same then print the same string
 Else run a for loop from L to R and swap the current element in the for
loop with the inputString[L]
 Then again call this same function by increasing the value of L by 1
 After that again swap the previously swapped values to initiate
backtracking

// Java program to print all permutations of a


// given string.
public class Permutation {

// Function call
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
Permutation p = new Permutation();
p.permute(str, 0, n - 1);
}

private void permute(String str, int l, int r)


{
if (l == r)
System.out.println(str);
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}

public String swap(String a, int i, int j)


{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}

// This code is contributed by Mihir Joshi


Output
ABC
ACB
BAC
BCA
CBA
CAB

Longest Palindromic Substring


Given a string str, the task is to find the longest substring which is a palindrome.
Examples:
Input: str = “forgeeksskeegfor”
Output: “geeksskeeg”
Explanation: There are several possible palindromic substrings like “kssk”, “ss”, “eeksskee”
etc. But the substring “geeksskeeg” is the longest among all.
Input: str = “Geeks”
Output: “ee”
Naive Approach for Longest Palindromic Substring:
Check each substring, if it is a palindrome or not and keep updating the longest palindromic
substring found till now.
Follow the steps mentioned below to implement the idea:
 Generate all the substrings.
o For each substring, check if it is palindrome or not.
o If substring is Palindrome, then update the result on the basis of longest palindromic
substring found till now.
// A Java solution for longest palindrome
import java.util.*;
class GFG {

// Function to print a subString str[low..high]


static void printSubStr(String str, int low, int high)
{
for (int i = low; i <= high; ++i)
System.out.print(str.charAt(i));
}

// This function prints the


// longest palindrome subString
// It also returns the length
// of the longest palindrome

static int longestPalSubstr(String str)


{
// Get length of input String
int n = str.length();

// All subStrings of length 1 are palindromes


int maxLength = 1, start = 0;

// Nested loop to mark start and end index


for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
int flag = 1;
// Check palindrome
for (int k = 0; k < (j - i + 1) / 2; k++)
if (str.charAt(i + k) != str.charAt(j - k))
flag = 0;

// Palindrome
if (flag != 0 && (j - i + 1) > maxLength) {
start = i;
maxLength = j - i + 1;
}
}
}

System.out.print(
"Longest palindrome substring is: ");
printSubStr(str, start, start + maxLength - 1);

// Return length of LPS


return maxLength;
}

// Driver Code
public static void main(String[] args)
{
String str = "forgeeksskeegfor";
System.out.print("\nLength is: " + longestPalSubstr(str));
}
}

Recursively remove all adjacent duplicates


Given a string, recursively remove adjacent duplicate characters from the string. The output
string should not have any adjacent duplicates. See the following examples.
Examples:
Input: azxxzy
Output: ay
 First “azxxzy” is reduced to “azzy”.
 The string “azzy” contains duplicates,
 so it is further reduced to “ay”.
Input: geeksforgeeg
Output: gksfor

Input: caaabbbaacdddd
Output: Empty String
Input: acaaabbbacdddd
Output: acac
The following approach can be followed to remove duplicates in O(N) time:
 Start from the leftmost character and remove duplicates at left corner if there are any.
 The first character must be different from its adjacent now. Recur for string of length n-1
(string without first character).
 Let the string obtained after reducing right substring of length n-1 be rem_str. There are
three possible cases
1. If first character of rem_str matches with the first character of original string,
remove the first character from rem_str.
2. If remaining string becomes empty and last removed character is same as first
character of original string. Return empty string.
3. Else, append the first character of the original string at the beginning of rem_str.
 Return rem_str.
Below image is a dry run of the above approach:

Below is the implementation of the above approach:


// Java program to remove all adjacent duplicates from a string
import java.io.*;
import java.util.*;

class GFG {

static char last_removed; // will store the last char


// removed during recursion

// Recursively removes adjacent duplicates from str and


// returns new string. last_removed is a pointer to
// last_removed character
static String removeUtil(String str)
{
// If length of string is 1 or 0
if (str.length() == 0 || str.length() == 1)
return str;

// Remove leftmost same characters and recur for


// remaining string
if (str.charAt(0) == str.charAt(1)) {
last_removed = str.charAt(0);
while (str.length() > 1 && str.charAt(0) == str.charAt(1))
str = str.substring(1, str.length());
str = str.substring(1, str.length());
return removeUtil(str);
}

// At this point, the first character is definitely


// different from its adjacent. Ignore first
// character and recursively remove characters from
// remaining string
String rem_str = removeUtil(str.substring(1, str.length()));

// Check if the first character of the rem_string


// matches with the first character of the original
// string
if (rem_str.length() != 0
&& rem_str.charAt(0) == str.charAt(0)) {
last_removed = str.charAt(0);

// Remove first character


return rem_str.substring(1, rem_str.length());
}

// If remaining string becomes empty and last


// removed character is same as first character of
// original string. This is needed for a string like
// "acbbcddc"
if (rem_str.length() == 0
&& last_removed == str.charAt(0))
return rem_str;

// If the two first characters of str and rem_str


// don't match, append first character of str before
// the first character of rem_str
return (str.charAt(0) + rem_str);
}
static String remove(String str)
{
last_removed = '\0';
return removeUtil(str);
}

// Driver code
public static void main(String args[])
{
String str1 = "geeksforgeeg";
System.out.println(remove(str1));

String str2 = "azxxxzy";


System.out.println(remove(str2));

String str3 = "caaabbbaac";


System.out.println(remove(str3));

String str4 = "gghhg";


System.out.println(remove(str4));

String str5 = "aaaacddddcappp";


System.out.println(remove(str5));

String str6 = "aaaaaaaaaa";


System.out.println(remove(str6));

String str7 = "qpaaaaadaaaaadprq";


System.out.println(remove(str7));

String str8 = "acaaabbbacdddd";


System.out.println(remove(str8));
}
}

Check if string is rotated by two places

Given two strings, the task is to find if a string can be obtained by rotating another string by two
places.
Examples:
Input: string1 = “amazon”, string2 = “azonam”
Output: Yes
Explanation: Rotating string1 by 2 places in anti-clockwise gives the string2.
Input: string1 = “amazon”, string2 = “onamaz”
Output: Yes
Explanation: Rotating string1 by 2 places in clockwise gives the string2.
// Java program to check if a string is two time
// rotation of another string.

class Test
{
// Method to check if string2 is obtained by string 1
static boolean isRotated(String str1, String str2)
{
if (str1.length() != str2.length())
return false;
if(str1.length() < 2)
{
return str1.equals(str2);
}

String clock_rot = "";


String anticlock_rot = "";
int len = str2.length();

// Initialize string as anti-clockwise rotation


anticlock_rot = anticlock_rot + str2.substring(len-2, len) + str2.substring(0, len-
2) ;

// Initialize string as clock wise rotation


clock_rot = clock_rot +str2.substring(2) + str2.substring(0, 2) ;

// check if any of them is equal to string1


return (str1.equals(clock_rot) ||
str1.equals(anticlock_rot));
}

// Driver method
public static void main(String[] args)
{
String str1 = "geeks";
String str2 = "eksge";

System.out.println(isRotated(str1, str2) ? "Yes"


: "No");
}
}

Length of the longest substring without


repeating characters
Given a string str, find the length of the longest substring without repeating characters.
Example:
Example 1:
Input: “ABCDEFGABEF”
Output: 7
Explanation: The longest substring without repeating characters are “ABCDEFG”,
“BCDEFGA”, and “CDEFGAB” with lengths of 7
// Java program to find the length of the longest substring without repeating characters
import java.io.*;
import java.util.*;

class GFG {

// This function returns true if all characters in


// str[i..j] are distinct, otherwise returns false
public static Boolean areDistinct(String str, int i, int j)
{

// Note : Default values in visited are false


boolean[] visited = new boolean[256];

for (int k = i; k <= j; k++) {


if (visited[str.charAt(k)] == true)
return false;

visited[str.charAt(k)] = true;
}
return true;
}

// Returns length of the longest substring


// with all distinct characters.
public static int longestUniqueSubsttr(String str)
{
int n = str.length();

// Result
int res = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.max(res, j - i + 1);

return res;
}

// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);

int len = longestUniqueSubsttr(str);

System.out.println("The length of the longest "


+ "non-repeating character "
+ "substring is " + len);
}
}

Longest Common Prefix using Sorting


Problem Statement: Given a set of strings, find the longest common prefix.
Examples:
Input: {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output: “gee”
Input: {“apple”, “ape”, “april”}
Output: “ap”
The longest common prefix for an array of strings is the common prefix between 2 most
dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common
prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any
starting characters.
// Java program to find longest common prefix of given array of words.
import java.util.*;

public class GFG


{
public String longestCommonPrefix(String[] a)
{
int size = a.length;

/* if size is 0, return empty string */


if (size == 0)
return "";

if (size == 1)
return a[0];

/* sort the array of strings */


Arrays.sort(a);

/* find the minimum length from first and last string */


int end = Math.min(a[0].length(), a[size-1].length());

/* find the common prefix between the first and


last string */
int i = 0;
while (i < end && a[0].charAt(i) == a[size-1].charAt(i) )
i++;

String pre = a[0].substring(0, i);


return pre;
}

/* Driver Function to test other function */


public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = {"geeksforgeeks", "geeks", "geek", "geezer"};
System.out.println( "The longest Common Prefix is : " +
gfg.longestCommonPrefix(input));
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy