Wednesday, March 29, 2017

Reverse each word of the string without reversing the order of the words

Input- India is great
Output- aidnI si taerg

String[] test = ("India is great").split(" ");

        String t = "";

        for(int i=0 ; i < test.length ; i++) {
            for (int j = test[i].length()-1; j>=0; j--) {
                t += test[i].charAt(j);
            }
            t += " ";
        }
        System.out.println(t);

Note- You need to implement additional logic to not have space after the last word

Monday, March 16, 2015

First non-repeated character in a String

Problem Statement- Given a string find out the first non-repeated character in it. e.g.
#1 if String is "test" then answer is e
#2 if String is "tested" then answer is s
#3 if String is "rotator" then answer is a

Assumption- There is at least one non-repeated character in the string

Implemention using Hashmap
import java.util.HashMap;
import java.util.Scanner;

public class nonRepeatedChar {

static char nonrepeatCharacter(String str) {
        HashMap<Character, Integer> hm= new HashMap<Character, Integer>();
        char c;
        int i;
        for(i=0;i<str.length();i++)
            {
            c=str.charAt(i);
         
            if(hm.containsKey(c))
            hm.put(c, hm.get(c).intValue() + 1);
            else
            hm.put(c, 1);
        }
        for(i=0;i<str.length();i++)
        {
        if(hm.get(str.charAt(i)).intValue()==1)
        break; // break the loop as soon as first character is found with a value of 1
        }
        System.out.println("Key set in the Hash map is " + hm);
     
        return str.charAt(i);
   }
public static void main(String[] args) {

Scanner in = new Scanner(System.in);
        String str;
        char c;
        str = in.next();
     
        c = nonrepeatCharacter(str);
        System.out.println("first non-repeated character in string is= " + c);

}

}

Input #1
test
Output #1
Key set in the Hash map is {e=1, t=2, s=1}
first non-repeated character in string is= e

Input #2
tested
Output #2
Key set in the Hash map is {d=1, e=2, t=2, s=1}
first non-repeated character in string is= s

Input #3
rotator
Output #3
Key set in the Hash map is {t=2, r=2, a=1, o=2}
first non-repeated character in string is= a

Input #4
a
Output #4
Key set in the Hash map is {a=1}

first non-repeated character in string is= a

Implemention without using Collection

static char nonrepeatCharacter(String str) {
     
        char c='  ';
        int i,j, count=0;
       
        char[] ch=str.toCharArray();
        for(i=0;i<str.length();i++)
        {
        c=ch[i];
       
        for(j=i+1;j<str.length();j++)
        {
        if(c==ch[j])
        break; /* Either this condition will satisfy and loop will be break or if the match
                                              has done with all the characters and this condition is not satisfied then                                                   that is the first non-repeated character in the string */
       
                        if(j==str.length()-1)
        count=1;
        }
        if(count==1)
        break;
        }
       
       return c;

   }

Tuesday, March 3, 2015

Sorting a Single String in Java using java.util.Arrays sort method

Following program depicts how to sort a single String in Java using java.util.Arrays sort method

String Sort(String S)
        {
        char ar[]=S.toCharArray();
        Arrays.sort(ar); // Will sort all characters in character array ar
        S=new String(ar);
        return S;

        }

Input#0
edf
Output#0
def

Input#1
mnd
Output#1
dmn

Input#2
abba
Output#2
aabb

Saturday, January 17, 2015

Implementing Queue using ArrayList

// Implementing queue using ArrayList
import java.util.*;

class Test
    {
    public static void main(String[] args) throws Exception
        {
        int T, q, num; // T: size of queue, q: query to be done 0- remove element, 1- add element
        // Note- In case of ArrayList, initial size is not mandatory since the ArrayList can grow / shrink it's size based on the number of elements. However there is an constructor where you can intialize the size of ArrayList, we will use that here
        Scanner sc=new Scanner(System.in);
        T=sc.nextInt();
        ArrayList<Integer> al= new ArrayList<Integer>(T);
        try
            {
        while(T>0)
            {
            al.add(sc.nextInt()); //Read queue elements from console
            T--;
        }
        q=sc.nextInt(); // Reading query to be done on queue 
        if(q!=0)
            {          
            al=enqueue(al, sc.nextInt()); // Reading number to be added to queue  and add it to queue
        }
        else
            al= dequeue(al); // if q is 0 remove the first element of queue since queue works in first in first out fashion
            printQueue(al); // Printing the queue
        }
        catch(Exception e)
            {
            System.out.println("Bad Input");
        }
     
    }
    public static ArrayList<Integer> enqueue(ArrayList<Integer> al, int num)
        {
        al.add(num);
        return al;
    }
    public static ArrayList<Integer> dequeue(ArrayList<Integer> al)
        {
        al.remove(0);
        return al;
    }
    public static void printQueue(ArrayList<Integer> al)
        {
        for(int i=0;i<al.size();i++)
                System.out.print(al.get(i)+" "); // Printing the queue
    }
}

Input#0
4
1 2 3 5
0
Output#0
2 3 5

Input#1
4
3 4 5 6
1
1000
Output#1
3 4 5 6 1000

Java- Playing with Strings: splitting, replacing character

This summary is not available. Please click here to view the post.

Thursday, January 8, 2015

Finding occurrences of a character in a string or of a word in a sentence using TreeMap

TreeMap

A TreeMap - 
  • Maintains entries in ascending order sorted on the Keys
  • Is efficient to traverse the entries in sorted order 
  • A duplicate entry overrides the previous one (Note- If the Key is character or String the a upper case and lower case will be treated as distinct keys where Upper case precedes lower case. This is because ascii value of upper case alphabets is lesser than lower case)
Finding occurrences of a character in a string using TreeMap

import java.io.*;
import java.util.*;


public class Solution {

 
 public static void main(String[] args) {
     Scanner sc= new Scanner(System.in);
     String str=sc.next(); // Reading a string from console, in case of a sentence use method nextLine()
   
     char ch[]=str.toCharArray(); // Splitting the string to a character array, use String.split method in case of finding occurrences for a word in sentence
     TreeMap<Character, Integer> tr= new TreeMap<Character, Integer>(); // Initializing a TreeMap where character as Key and a integer counter to count the occurences of the character
     for(int i=0;i<str.length();i++)
         {
         if(tr.get(ch[i])==null) // If character is not present add that to the map with a value (counter) 1
             tr.put(ch[i], 1);
         else // If character already exists in the map get the value of it and increment it before adding the chacter again to Map
             {
             int value= tr.get(ch[i]).intValue();
             value++;
             tr.put(ch[i], value);
         }
             }
     System.out.println(tr); // Print all the character and their occurrences in ascending order of Key
     System.out.println("Occurences of 'a'= " + tr.get('a').intValue()); // Print occurrences of character 'a'
   }
}

Input# 0

anurag

Output# 0

{a=2, g=1, n=1, r=1, u=1}


Occurrences of 'a'= 2

Wednesday, January 7, 2015

Finding an Element & it's index in a list (Using TreeSet)

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args)
{
         int V, n; // V is the number to be searched, n is the size of list

        Scanner sc=new Scanner(System.in);
        V=sc.nextInt();
        n=sc.nextInt();

        TreeSet<Integer> ar1= new TreeSet<Integer>();
        while(sc.hasNext()) // Read input till it exists
            {
                    ar1.add(sc.nextInt());
            }
                if(ar1.contains(V))
                System.out.println(ar1.headSet(V).size()); /* headSet(element) returns the sub-TreeSet of elements less than its argument, so the size of this set will be the index of the element in question. A strange solution indeed.*/
    }
}

Another solution for this problem using Array

public class Solution {

    public static void main(String[] args) {
     
        int V, n, i=0; // V is the number to be searched, n is the size of list
        boolean found=false;
        Scanner sc=new Scanner(System.in);
        V=sc.nextInt();
        n=sc.nextInt();
        int ar[]= new int[n];
        while(n>i)
            {
            ar[i]=sc.nextInt();
            i++;
            }
        //System.out.println(i);
        for(i=0;i<n;i++)
            if(ar[i]==V)
            {
            System.out.println(i);
            found=true;
            break;
        }
        if(!found)
            System.out.println(0);
    }

}