0% found this document useful (0 votes)
13 views7 pages

String Manipulation Problems Solutions

Uploaded by

akankshyatarenia
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)
13 views7 pages

String Manipulation Problems Solutions

Uploaded by

akankshyatarenia
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

1. Leetcode q.

28 Given two strings needle and haystack, return the index of the first
occurrence of needlein haystack, or -1 if needle is not part of haystack.

Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

class Solution {
public static int strStr(String haystack, String needle) {
int nee_len=[Link]();
int hay_len=[Link]();
String sub;
for(int i=0;i<=hay_len-nee_len;i++){
sub = [Link](i,i+nee_len);
if([Link](sub)){
return i;
}
}
return -1;
}
public static void main(String args[]){
Scanner ss=new Scanner([Link]);
String hay=[Link]();
String nee=[Link]();
strStr(hay,nee);
}
}

2. Isomorphic strings--

class Solution {
public static boolean isIsomorphic(String s, String t) {
if([Link]()!=[Link]()){
return false;
}
Map<Character,Character> map=new HashMap<>();
for(int i=0;i<[Link]();i++){
char str1=[Link](i),str2=[Link](i);
if([Link](str1)){

if([Link](str1)!=str2){
return false;
}

}
else {
if([Link](str2)){
return false;
}

[Link](str1,str2);

}
}
return true;
}

public static void main(String args[]){


Scanner ss=new Scanner([Link]);
String s=[Link]();
String t=[Link]();
isIsomorphic(s,t);
}
}

(OR)

import [Link];

public class IsomorphicStrings {


public static boolean areIsomorphic(String s, String t) {
if ([Link]() != [Link]()) {
return false;
}

HashMap<Character, Character> sToT = new HashMap<>();


HashMap<Character, Character> tToS = new HashMap<>();

for (int i = 0; i < [Link](); i++) {


char charS = [Link](i);
char charT = [Link](i);
// Check s to t mapping
if ([Link](charS)) {
if ([Link](charS) != charT) {
return false; // Not isomorphic
}
} else {
[Link](charS, charT);
}

// Check t to s mapping
if ([Link](charT)) {
if ([Link](charT) != charS) {
return false; // Not isomorphic
}
} else {
[Link](charT, charS);
}
}

return true;
}

public static void main(String[] args) {


// Example 1
String s1 = "egg";
String t1 = "add";
[Link](areIsomorphic(s1, t1)); // Output: true

// Example 2
String s2 = "foo";
String t2 = "bar";
[Link](areIsomorphic(s2, t2)); // Output: false

// Example 3
String s3 = "paper";
String t3 = "title";
[Link](areIsomorphic(s3, t3)); // Output: true
}
}

3. Reverse vowels of a string---

Example 1:

Input: s = "hello"
Output: "holle"
Example 2:

Input: s = "leetcode"
Output: "leotcede"

class Solution {
public String reverseVowels(String s) {
char[] c=[Link]();
int start=0;
int end=[Link]()-1;
while(start<end){
while(start<end && !isVowel(c[start])){
start++;
}
while(start<end && !isVowel(c[end])){
end--;
}
if(start<end){
char temp=c[start];
c[start]=c[end];
c[end]=temp;
start++;
end--;
}
}
return new String(c);
}
public static boolean isVowel(char c){
return "aeiouAEIOU".indexOf(c) != -1;
}
}

4.

A chocolate factory is packing chocolates into the packets. The chocolate


packets here represent an array of N number of integer values. The task
is to find the empty packets(0) of chocolate and push it to the end of the
conveyor belt(array).

Example 1 : N=8 and arr = [4,5,0,1,9,0,5,0]. There are 3 empty packets


in the given set. These 3 empty packets represented as O should be
pushed towards the end of the array

Input : 8 – Value of N
[4,5,0,1,9,0,5,0]

Output: 4 5 1 9 5 0 0 0

import [Link].*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
int n=[Link]();
int arr[]=new int[n];
for(int i=0;i< n;i++)
arr[i]=[Link]();
int count=0;
for(int i=0;i< n;i++)
if(arr[i]!=0)
arr[count++]=arr[i];
for(int i=count;i < n;i++)
arr[i]=0;
for(int i=0;i< n;i++)
[Link](arr[i]+" ");
}
}

5. Palindrome
class Solution {
public boolean isPalindrome(int x) {
int old=x,s,rev=0;
while(x>0){
s=x%10;
rev=(rev*10)+s;
x=x/10;
}
return (rev==old);
}
}

6. Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is
written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX +
V + II.

///////SWITCH STATEMENTS///////
class Solution {
public int romanToInt(String s) {
int prev=0,ans=0,num=0;
for(int i=[Link]()-1;i>=0;i--){
switch([Link](i)){
case 'I'-> num=1;
case 'V'-> num=5;
case 'X'-> num=10;
case 'L'-> num=50;
case 'C'-> num=100;
case 'D'-> num=500;
case 'M'-> num=1000;
}
if(num < prev){
ans -= num;
}
else{
ans += num;
}
prev=num;
}
return ans;
}
}

7. Write a function to find the longest common prefix string amongst an array of
strings.
If there is no common prefix, return an empty string "".

Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

//////////
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || [Link] == 0) {
return "";
}

StringBuilder sb = new StringBuilder();

for (int j = 0; j < strs[0].length(); j++) {


char c = strs[0].charAt(j);
for (int i = 1; i < [Link]; i++) {
if (j >= strs[i].length() || strs[i].charAt(j) != c) {
return [Link]();
}
}
[Link](c);
}

return [Link]();
}
}

Common questions

Powered by AI

The algorithm iterates through the array and maintains a count of non-empty packets, shifting them towards the beginning of the array. Afterward, it fills the remaining positions from the count to the end of the array with zeros, effectively pushing all empty packets to the end .

The solution checks each character position sequentially across all strings until a mismatch is found, appending matched characters to the result. While simple, this method can be inefficient with a large number of strings or very long strings due to the repeated comparisons across all strings for each character position .

To enhance the solution, consider implementing a more efficient data structure, like a combined two-way mapping with hashmaps, to reduce the overhead of checking two separate mappings. Additionally, use parallel processing or hash-based techniques to quickly identify potential non-isomorphic strings, improving the performance over large datasets .

The computation is valid as it checks each character position across all strings and exits the loop upon finding a mismatch. This ensures that only characters present at the same position in all strings are included in the prefix, thereby maintaining the validity of the longest common prefix across the array .

The algorithm is reliable for straightforward string matching but can be inefficient with long strings due to its O(n*m) complexity, where n is the length of the haystack and m the length of the needle. An improvement would be using algorithms like KMP (Knuth-Morris-Pratt), which preprocesses the needle to allow linear time complexity searches .

Reversing the integer’s digits and comparing it to the original is effective for determining if it is a palindrome, as a palindromic number reads the same forward and backward. This method directly validates the property by reconstructing the number and can handle positive integers efficiently .

The approach involves two pointers: one starting from the beginning and another from the end of the string. These pointers move towards each other, swapping vowels when encountered. The process continues until the pointers meet. This ensures vowels are reversed while all non-vowel characters remain in their place .

The function uses a switch statement to convert each Roman symbol to its integer value, iterating from the last character to the first. It subtracts values only when the current numeral is smaller than the previous, handling cases like 'IX' or 'CM' where subtraction is needed. Otherwise, it adds the numeral’s value to the result .

The solution ensures two strings are isomorphic by mapping characters from one string to the other using a HashMap. Moreover, it checks for reverse mapping to ensure no two different characters map to the same character. If both conditions hold true without contradictions throughout the strings, the strings are isomorphic .

The function iterates over the 'haystack' string and extracts substrings starting from each index, with a length equal to the 'needle'. It compares these substrings to the 'needle' for equality. If a match is found, it returns the current index. In the 'sadbutsad' example, 'sad' first appears at index 0, so the function returns 0 .

You might also like