KEMBAR78
String Questions | PDF | String (Computer Science) | Software Development
0% found this document useful (0 votes)
21 views9 pages

String Questions

The document contains multiple Java code snippets demonstrating various programming tasks, including reversing strings, finding the longest common prefix, checking for K-anagrams, identifying pangrams, converting Roman numerals to integers, checking divisibility by 7, counting substrings with equal numbers of 0s, 1s, and 2s, replacing substrings, and maximizing the sum of minimum values in fruit pairs. Each task is explained with input examples and corresponding output. The code snippets are designed to be run in an online Java compiler.

Uploaded by

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

String Questions

The document contains multiple Java code snippets demonstrating various programming tasks, including reversing strings, finding the longest common prefix, checking for K-anagrams, identifying pangrams, converting Roman numerals to integers, checking divisibility by 7, counting substrings with equal numbers of 0s, 1s, and 2s, replacing substrings, and maximizing the sum of minimum values in fruit pairs. Each task is explained with input examples and corresponding output. The code snippets are designed to be run in an online Java compiler.

Uploaded by

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

1.

Reverse the Given String


Input: str = “I like this program very much”
Output: str = “much very program this like i”
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public void reverse(String str){
String[] words=str.split(" ");
String revstr="";
for(int i=words.length-1;i>=0;i--){
revstr=revstr+words[i]+" ";
}
System.out.println(revstr);
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String str="geoks for geeks";
Main m1=new Main();
m1.reverse(str);
}
}

----------Using Stack-------------
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public void reverse(String str){
Stack<String> stack=new Stack<>();
StringBuilder str1 = new StringBuilder();
for(int i=0;i<str.length();i++){
if(str.charAt(i) != '.'){
str1.append(str.charAt(i));
}
else{
stack.push(str1.toString());
str1.setLength(0);
}
}
stack.push(str1.toString());
StringBuilder revstr= new StringBuilder();
while (!stack.isEmpty()) {
revstr.append(stack.pop());
if (!stack.isEmpty()) {
revstr.append(".");
}
}
System.out.println(revstr.toString());
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String str="geoks.for..geeks";
Main m1=new Main();
m1.reverse(str);
}
}
2.Given an array of strings arr[], the task is to return the longest common prefix
among each and every strings present in the array. If there’s no prefix common in
all the strings, return “”.

Examples:

Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]


Output: “gee”
Explanation: “gee” is the longest common prefix in all the given strings:
“geeksforgeeks”, “geeks”, “geeks” and “geezer”.

Code:
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public void longCommonPre(String[] arr){
Arrays.sort(arr);
String first=arr[0];
String last=arr[arr.length-1];
int minlen=Math.min(first.length(),last.length());
int i=0;
while(i<minlen && first.charAt(i)==last.charAt(i)){
i++;
}
System.out.println(first.substring(0,i));
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String[] arr = {"apple", "app", "ap", "ol" };
Main m1=new Main();
m1.longCommonPre(arr);
}
}

3.Given two strings of lowercase alphabets and a value k, the task is to find if
two strings are K-anagrams of each other or not.
Two strings are called k-anagrams if following two conditions are true.

Both have same number of characters.


Two strings can become anagram by changing at most k characters in a string.
Examples :

Input: str1 = "anagram" , str2 = "grammar" , k = 3


Output: Yes
Explanation: We can update maximum 3 values and
it can be done in changing only 'r' to 'n'
and 'm' to 'a' in str2.

Code:
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public void AnagramK(String str1,String str2,int k){
int Max_char=26;
int[] count1=new int[Max_char];
int[] count2=new int[Max_char];
int count=0;
for(int i=0;i<str1.length();i++){
count1[str1.charAt(i)-'a']++;
}
for(int i=0;i<str1.length();i++){
count2[str2.charAt(i)-'a']++;
}
for(int j=0;j<Max_char;j++){
if(count1[j]>count2[j]){
count=count+Math.abs(count1[j]-count2[j]);
}
}
if(count<k){
System.out.println("Anagram possible");
}
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String str1="grammar";
String str2="anagram";
int k=3;
Main m1=new Main();
m1.AnagramK(str1,str2,k);
}
}

4.Given a string s, the task is to check if it is Pangram or not. A pangram is a


sentence containing all letters of the English Alphabet.
Examples:
Input: s = “The quick brown fox jumps over the lazy dog”
Output: true
Explanation: The input string contains all characters from ‘a’ to ‘z’.

Code:
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public void panagram(String str){
if(str.length()==0 || str.length()<26){
System.out.println("Not panagram");
}
else{
int count=0;
ArrayList<Integer> list = new ArrayList<>(Collections.nCopies(26, 1));

for(int i=0;i<str.length();i++){
char s=str.charAt(i);
int a=Character.toLowerCase(s)-'a';
if(a>=0){
if(s!=' ' && list.get(a)==1){
list.set(a,0);
count++;
}
}
}
if(count==26){
System.out.println("Panagram "+count);
}
else{
System.out.println("Not Panagram "+count+" "+str.length());
}
}
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String str="How vexingly quick daft zebras jump!";
Main m1=new Main();
m1.panagram(str);
}
}

5.Given a string in roman form, the task is to convert this given roman string into
an integer.

Roman numerals are based on the symbols I, V, X, L, C, D, and M, which represent 1,


5, 10, 50, 100, 500, and 1,000 respectively. Different arrangements of these
symbols represent different numbers. The roman numbers I, II, III, IV, V, VI, VII,
VIII, IX, and X represent 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 respectively.

How does the conversion work?

If a smaller value symbol comes before, we subtract. Otherwise, we add.


In IV, I comes before V and V has a larger value 5. So our result is 5 – 1 = 4.
In VI, V comes before I and I has a smaller value 1. So our result is 5 + 1 = 6.
In II, we have same values, so we add and get 1 + 1 = 2
In case of more than 2 characters, we traverse from left to right and group only
when we see a greater value character after a smaller value character. For example
MXVII is 1000 + 10 + 5 + 1 + 1 = 1017. And XLVII is (50 – 10) + 5 + 1 + 1 = 47.
Note that L is larger and comes after X.
Examples:

Input: s = “IX”
Output: 9
Explanation: IX is a Roman symbol which represents 10 – 1 = 9

Input: s = “XL”
Output: 40
Explanation: XL is a Roman symbol which represents 50 – 10 = 40

Input: s = “MCMIV”
Output: 1904
Explanation: M is 1000, CM is 1000 – 100 = 900, and IV is 4. So we have total as
1000 + 900 + 4 = 1904

Code:
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
public int helper(char ch){
switch(ch){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
return 0;
}
public void Romtoint(String str){
int res=0;
for(int i=0;i<str.length();i++){
int i1=helper(str.charAt(i));
int j=i+1;
if(j<str.length()){
int i2=helper(str.charAt(j));
System.out.println(i1+" "+i2);
if(i1==i2 || i1>i2){
res=res+i1;
}
else if(i1<i2){
res=res+(i2-i1);
i++;
}
}
else{
res=res+i1;
}
}
System.out.println(res);
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String str="VIIM";
Main m1=new Main();
m1.Romtoint(str);
}
}

6.Given a number N, the task is to check if it is divisible by 7 or not.


Note: You are not allowed to use the modulo operator, floating point arithmetic is
also not allowed.
Naive approach: A simple method is repeated subtraction.
Code:
import java.util.*;
class Main {
public void divisible7(int d){
int i=d;
while(i>=0 || i<0){
if(i<0){
System.out.println("Not divisible by: 7 "+"Remainder: "+i);
break;
}
else if(i==0){
System.out.println("divisible by: 7 "+"Remainder: "+i);
break;
}
i=i-7;
}
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
int d=343;
Main m1=new Main();
m1.divisible7(d);
}
}

7.Given a string that consists of only 0s, 1s and 2s, count the number of
substrings that have an equal number of 0s, 1s, and 2s.
Examples:
1.Input: str = “0102010”
Output: 2
Explanation: Substring str[2, 4] = “102” and substring str[4, 6] = “201” has equal
number of 0, 1 and 2
2.Input: str = “102100211”
Output: 5

Code:
// Java program to find substring with equal
// number of 0's, 1's and 2's

import java.util.*;

public class GFG {

// Method to count number of substring which


// has equal 0, 1 and 2
static long getSubstringWithEqual012(String s)
{

ArrayList<String> arr = new ArrayList<>();


int n = s.length();
// generating subarrays
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
String s1 = "";
for (int k = i; k <= j; k++) {
s1 += s.charAt(k);
}
arr.add(s1);
}
}
int count = 0;
int countZero, countOnes, countTwo;
// iterating over array of all substrings
for (int i = 0; i < arr.size(); i++) {
countZero = 0;
countOnes = 0;
countTwo = 0;
String curs = arr.get(i);
for (int j = 0; j < curs.length(); j++) {
if (curs.charAt(j) == '0')
countZero++;
if (curs.charAt(j) == '1')
countOnes++;
if (curs.charAt(j) == '2')
countTwo++;
}
// if number of ones,two and zero are equal in a
// substring
if (countZero == countOnes
&& countOnes == countTwo) {
count++;
}
}

return count;
}
// Driver's code
public static void main(String[] args)
{
String str = "0102010";
System.out.println(getSubstringWithEqual012(str));
}
}

8.Given three strings S, S1, and S2 consisting of N, M, and K characters


respectively, the task is to modify the string S by replacing all the substrings S1
with the string S2 in the string S.

Examples:
Input: S = “abababa”, S1 = “aba”, S2 = “a”
Output: aba
Explanation:
Change the substrings S[0, 2] and S[4, 6](= S1) to the string S2(= “a”) modifies
the string S to “aba”. Therefore, print “aba”.
Input: S = “geeksforgeeks”, S1 = “eek”, S2 = “ok”
Output: goksforgoks

Code:
Method1:-
class Main {
public void replaceSubstrWithStr(String S,String S1,String S2){
String result=S.replace(S1,S2);
System.out.println(result);
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
Main r1=new Main();
r1.replaceSubstrWithStr("geeksforgeeks","eek","ok");
}
}

Method2:-
class Main {
public void replaceSubstrWithStr(String S,String S1,String S2){
String result="";
int s1_len=S1.length();
for(int i=0;i<S.length();){
if(i<S.length()-2 && S.substring(i, i + s1_len).equals(S1)){
result=result+S2;
i=i+s1_len;
}
else{
result=result+S.charAt(i);
i++;
}
}
System.out.println(result);
}
public static void main(String[] args) {
System.out.println("Try programiz.pro");
Main r1=new Main();
r1.replaceSubstrWithStr("abacaba","aba","a");
}
}

9.Reena has a basket containing an array of 2N fruits.


She needs to pair these fruits into N pairs, (a1, b1) , (a2, b2),.....,(an, bn),
such that the sum of the minimum values in each pair, min(ai, bi) for all i is
maximized.
Your task is to calculate and print this maximum possible sum.
Testcase Input
6
5 3 2 1 6 3
Testcase Output
9
Explanation
As to get maximum sum in this case our answer would be
Min(1,2) + min(3,3) + min(5,6) = 9

Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Solution{
public void maxSum(String[] arr,int n){
Arrays.sort(arr);
int[] arr1=new int[n];
int max=0;
for(int i=0;i<n;i++){
arr1[i]=Integer.parseInt(arr[i]);
}
for(int j=0;j<n;j+=2){
max=max+arr1[j];
}
System.out.println(max);
}
}
class Main {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT.
Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String[] arr=sc.nextLine().split(" ");
Solution s1=new Solution();
s1.maxSum(arr,n);
}
}

You might also like