Data Structures For Placement Training (Strings) - 18.10.2023
Data Structures For Placement Training (Strings) - 18.10.2023
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”
// 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);
}
// 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);
// Driver Code
public static void main(String[] args)
{
String str = "forgeeksskeegfor";
System.out.print("\nLength is: " + longestPalSubstr(str));
}
}
class GFG {
// Driver code
public static void main(String args[])
{
String str1 = "geeksforgeeg";
System.out.println(remove(str1));
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);
}
// Driver method
public static void main(String[] args)
{
String str1 = "geeks";
String str2 = "eksge";
class GFG {
visited[str.charAt(k)] = true;
}
return true;
}
// 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);
if (size == 1)
return a[0];