Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Wednesday, March 30, 2022

Interview Question: Sub String Palindrome using java.

Recent day interviews you may faced this question in programing interview. Find the sub string palindrome of given string input.

We have many way to solve it. Here I added coding snippet which I tried to solve it.

First one I used two for loop to solve it. Its very simple and easy.


private static List<String> subStringPalindrome(String value) {
List<String> list = new ArrayList<>();
for(int i =0 ; i < value.length(); i++){
for(int j = i+1 ; j < value.length(); j++){
StringBuffer s1 = new StringBuffer(value.substring(i,j));
String s2 = s1.reverse().toString();
if(value.substring(i,j).contentEquals(s2) && s1.length()> 1){
list.add(s1.toString());
}

}
}
return list;
}
List<String> list = subStringPalindrome("eetestseeammadam");
Output: [ee, ete, estse, sts, ee, amma, mm, ada]
Its very simple and easy. This code look simple and easy  and I tried another way using recursion.

private static List<String> printPalindromeSubString(String value;) {
List<String> list = new ArrayList<>();
if(value.equals(new StringBuilder(value).reverse()))
list.add(value);
for(int i=0; i <= value.length(); i++){
if(i > 1 && i < value.length() -1){
StringBuffer reverse = new StringBuffer(value.substring(i-2, i+1));
if(value.substring(i-2, i+1).contentEquals(reverse.reverse())){
System.out.println("Called2");
list.add(value.substring(i-2, i+1));
if(i>2){
if(i+2 <= value.length()){
new Test().callRecursion(value,value.substring(i-2, i+1), i-1, i, list );
}
}
}
}
if(i > 0 && i < value.length() ){
StringBuffer stringBuffer = new StringBuffer(value.substring(i-1, i+1));
if(value.substring(i-1, i+1).contentEquals(stringBuffer.reverse())){
list.add(value.substring(i-1, i+1));
System.out.println("Called");
if(i > 1){
new Test().callRecursion(value,value.substring(i-1, i+1), i, i, list );
}
}
}
}
return list;
}

private List<String> callRecursion(String value, String reversed, int i, int j, List<String> list){
if(j+1 >= value.length())
return list;
else if(value.charAt(i-2) == value.charAt(j+1)){
String s = value.charAt(i-2) +reversed+ value.charAt(j+1);
list.add(s);

callRecursion(value, s, i-1, j+1, list);
}
System.out.println(list);
return list;
}
List<String> list = printPalindromeSubString("eetestseeammadam");
Here i used recursion to find palindrome on given substring. And the output is 
[ee, ete, sts, estse, ee, mm, amma, ada, madam]

And the output is  If you check the output from two logic, there is a mismatch.. First one print only 8 palindrome and recursion logic print 9 palindrome. 'madam' missing in first logic. 
Lets make this blog more interactive with techies, Please find the missing condition or part of code on comment area.✌✌ 

Thanks in advance.

Tuesday, March 1, 2022

Immutable String in Java.

This is very popular interview question in core java interview. Most of us will answer it, String is immutable. When the question is goes why String is immutable, few of us only answer it, due to misunderstanding of immutable.

Here we will discuss about why?.

Immutable is,  once a string object created in string pool or heap we cannot change the value of it. But we can change the value of the reference. That's what we are doing in below code.

String name = "Boomi";
name = "raj";

But we are able to change it right??. Its not what immutable means. Immutable means we cannot edit the "Boomi" from string pool. Let see how above string stored in java memory.

When we create name = "Boomi"value "Boomi" will be create in string pool and assigned this value to name reference.


When we reassign the value "raj" to name. "raj" value will be created in string pool and this value is referred to name variable. But still "Boomi" value is there in string pool and reference to name is removed. This is why string is called immutable.

Now you may have a question why java engineers made string as immutable. 

Let see an example to understand why string immutable? 

String name = "Boomi";
String userName = "Boomi";

Here we are creating two string with same name. If String is mutable then we need to create two time value "Boomi". So it might consume lot of memory for real time application. 

Another reason for String immutability is security. 


Let change name value to "Boomiraj".

name = "Boomiraj";



New Object will be created for "Boomiraj" this referred to name variable. userName still referring to the "Boomi".

We know we can create String object two ways, 

  • by using "". eg String name = "Boomi"; //Object stored in string pool
  • by using new. eg String userName = new String("Boomi");//Object stored in heap memory.
String name = "Boomi";
String userName = "Boomiraj";
String nameObj = new String("Boomi");
String userNameObj = new String("Boomiraj");




Let check the both name and userName not pointing to same object by using ==

System.out.println(name == nameObj); //false
System.out.println(userName == userNameObj);//false

Thursday, February 24, 2022

How to Check if an Array Contain Duplicate In Java?

Hello All, 

Here the coding snippet to check duplicate in array. I used char[] to check the duplicate character check in a string. 


private static void findDuplicate(String input){
char[] strChar = input.toCharArray();
boolean haveDuplicate = false;
for(int i = 0 ; i < input.length(); i++){
for(int j = i+1 ; j < input.length(); j++){
if(strChar[i] == strChar[j]){
haveDuplicate = true;
System.out.print(strChar[i]);
}
}
}
if(!haveDuplicate){
System.out.println("No duplicate found in array");
}
}
Let pass input as "Java".
Output : a

Pass input as "Python"
Output : No duplicate found in array

Tuesday, December 28, 2021

Print Number of occurrences of each character from a string.

 Print the Number of occurrences of character form a string, we have many solution to solve this.

Here I posted a simple way I used to print number of occurrences of each character. 


private static void occurrenceOfChar(String input) {
int length = input.length();
char[] inputArray = input.toCharArray();
while(input.length() > 0){
input = input.replace(inputArray[0]+"", "");
System.out.println(inputArray[0] +" Occurrences is " + (length - input.length()));
inputArray = input.toCharArray();
length = input.length();
}
}
Input : Helloworld
Output : 
H Occurrences is 1
e Occurrences is 1
l Occurrences is 3
o Occurrences is 2
W Occurrences is 1
r Occurrences is 1
d Occurrences is 1


Thursday, October 10, 2019

String Manupulation Interview Questions

I/P : "ABC","DEF","GHI","JKL","MNO" (1,2,3,4,..N)
O/P:"ABC","MNO","DEF","JKL","GHI" (1,N-1,2,N-2.....)

Logic :


    public static void main(String[] args) {

        String[] str = { "ABC", "DEF", "GHI", "JKL", "MNO" };

        int ln = str.length - 1;
        for (int i = 0, j = ln; i <= j; i++, j--) {
            if (i == j) {
                System.out.println(str[i]);
            } else {
                System.out.println(str[i]);
                System.out.println(str[j]);
            }
        }

    }

Thursday, October 12, 2017

Fun Game : FLAMES Calculator.

In School time every one had tried out this game seriously/secretly with your dream one name. So we all know the rules of the game right?!.

 Lets look it into coding,

Here i have done the coding for this fun game,


/**
* Do flames check.Here we are finding the number of unmatched characters in both name.
*
* @param p_sYourName the p s your name
* @param p_sPartnerName the p s partner name
*/
private static void doFlamesCheck(String p_sYourName, String p_sPartnerName) {
int l_iUnLength = p_sYourName.length();
int l_iPnLength = p_sPartnerName.length();
for (int i = 0; i < p_sYourName.length(); i++) {
Loop: for (int j = 0; j < p_sPartnerName.length(); j++) {
if (p_sYourName.charAt(i) == p_sPartnerName.charAt(j)) {
l_iUnLength--;
l_iPnLength--;
break Loop;
}
}
}

int count = l_iUnLength + l_iPnLength;
doFlames(count);
}


/**
* Do flames.Here we find the character for the flame.
*
* @param val the val
*/
private static void doFlames(int val) {
String l = "FLAMES";
while (l.length() > 1) {
int k = val % l.length();
if (k != 0) {
l = l.substring(k, l.length()) + l.substring(0, k - 1);
}
if (k == 0) {
l = l.substring(0, l.length() - 1);
}

}
findRelation(l.charAt(0));
}


/**
* Find relation. Here just to print the relationship between both depends on doFlames() return char.
*
* @param rel the rel
*/
private static void findRelation(char rel) {
switch (rel) {
case 'F':
System.out.println("friendship");
break;
case 'L':
System.out.println("Love");
break;
case 'A':
System.out.println("Affection");
break;
case 'M':
System.out.println("Marriage");
break;
case 'E':
System.out.println("Enemy");
break;
case 'S':
System.out.println("Sister");
break;

default:
System.out.println("--");
break;
}
}

       /**
* The main method. Get the input from user to find the flames relationship.
*
* @param args the arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your Name : ");
String l_sYourName = input.next();
System.out.println("Enter Your Partner Name : ");
String l_sPartnerName = input.next();
doFlamesCheck(l_sYourName, l_sPartnerName);
}

NOTE: Please share your comments to improve the blog. Thank you.!

Tuesday, December 18, 2012

count character for number

/**
 *
 */
package com;

/**
 * @author Boomiraj
 *
 */
public class CountChar {

    /**
     * @param args
     */
    static int count = 0;
    public static void main(String[] args) {
        onecountCharacter();
    }
    public static void onecountCharacter(){
        String[] ones = {"zero","one","two","three","four","five","six","seven","eight","nine"};
        String[] ten = {"ten","eleven","twelve","thriteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
        String[] tens = {"twenty","thirty","fourty","fifty","sixty","seventy","eighty","nighty"};
      
 for(int i = 0; i < 100; i++){
//            Check whether the number is not greater then ten
            if(i<10){
                count = count + ones[i].length();
                System.out.println(ones[i] + " : " + i + " : " + count);
            }
//            Check whether the number is not greater than 9 and less than 20
            if(i>9 && i<20){
                int j = 10;
                j = i - j; //
                count = count + ten[j].length();
                System.out.println(ten[j] + ":" + i + " : " + count);
                j++;
            }
//            Check whether then number is greater then 20
            if(i>19){
                int k = i/10-2;
                int j = i % 10;
               
                if(j == 0){
                    count = count + tens[k].length();
                    System.out.println(tens[k] + " : "  + count);
                } else{
                    count = count + tens[k].length() + ones[j].length();
                    System.out.println(tens[k] + ones[j] + ":" + i + " :" + count);
                   
                }
                   
               
            }
           
        }
        System.out.println(count);
       
    }

}

Saturday, December 15, 2012

print the sentence from paragraph

public static String printSentance(String str) {
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '.' ) {
                strBuffer.append(str.charAt(i));

            } else {
                System.out.println(strBuffer);
                strBuffer = new StringBuffer();
            }
        }
        return strBuffer.toString();
    }

count number of sentence in paragraph(sentence end with '.' or '?')

public static int countNoOfSentance(String str){
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '.' && str.charAt(i) != '?') {
                strBuffer.append(str.charAt(i));

            } else {
                ++count;
                strBuffer = new StringBuffer();
            }
        }
        count++;
        System.out.println(count);
        return count;
    }


split the sentance when capital letter occur

//split the sentence manually 

public static String getSplit(String str){
        char[] str_1 = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        StringBuffer sbuffer = new StringBuffer();
        for(int i = 0; i<str.length();i++){
            for(int j = 0; j<str_1.length; j++){
               
                if(str.charAt(i) == str_1[j]){
                    sbuffer.append(" ");
                }
            }
            sbuffer.append(str.charAt(i));
        }
        return sbuffer;
    }

//split the sentence using API method
public static String getSplitByMethod(String str){
        StringBuffer sbuffer = new StringBuffer();
        for(int i = 0;i<str.length();i++){
            if(Character.isUpperCase(str.charAt(i))){
                sbuffer.append(" ").append(str.charAt(i));
            }else{
                sbuffer.append(str.charAt(i));
            }
        }
        return sbuffer.toString();
    }