Showing posts with label Data Structures. Show all posts
Showing posts with label Data Structures. Show all posts

Print the string after the specified character has occurred given no. of times

Given a string, a character, and a count, the task is to print the string after the specified character has occurred count number of times.Print “Empty string” in case of any unsatisfying conditions.(Given character is not present, or present but less than given count, or given count completes on last index). If given count is 0, then given character doesn’t matter, just print the whole string.

// Java program for above implementation 

public class GFG 
// Method to print the string 
static void printString(String str, char ch, int count) 
int occ = 0, i; 
// If given count is 0 
// print the given string and return 
if (count == 0) { 
System.out.println(str); 
return; 
// Start traversing the string 
for (i = 0; i < str.length(); i++) { 
// Increment occ if current char is equal 
// to given character 
if (str.charAt(i) == ch) 
occ++; 
// Break the loop if given character has 
// been occurred given no. of times 
if (occ == count) 
break; 
// Print the string after the occurrence 
// of given character given no. of times 
if (i < str.length() - 1) 
System.out.println(str.substring(i + 1)); 
// Otherwise string is empty 
else
System.out.println("Empty string"); 
// Driver Method 
public static void main(String[] args) 
String str = "geeks for geeks"; 
printString(str, 'e', 2); 


Examples:

Input  :  str = "This is demo string" 
          char = i,    
          count = 3
Output :  ng

Input :  str = "geeksforgeeks"
         char = e, 
         count = 2
Output : ksforgeeks

Count frequency of characters in a string

Use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.

HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk"; 

for (int i = 0; i < s.length(); i++)
 {
        char c = s.charAt(i);
        Integer val = map.get(c);
       
        if (val != null) { 
                                  map.put(c, new Integer(val + 1));
                                } else { 
                                              map.put(c, 1);
                                            }
                                }
}

Reverse a String

There are many ways of reversing a String in Java for whatever reason you may have. Today, we will look at a few simple ways of reversing a String in Java.

Method 1:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";

for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}

System.out.println("Reversed string is:");
System.out.println(reverse);
}
}

Method 2:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--)
{
sb.append(str.charAt(i));
}

System.out.println("Reversed string is:");
System.out.println(sb.toString());
}
}

Method 3:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder(str);

System.out.println("Reversed string is:");
System.out.println(sb.reverse().toString());
}
}

Print the duplicate elements of an array

In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.



public class DuplicateElement {
public static void main(String[] args) {

//Initialize example array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};

System.out.println("Duplicate elements in given array: ");

//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
    for(int j = i + 1; j < arr.length; j++) {
                            if(arr[i] == arr[j])
                             System.out.println(arr[j]);
}}}}

OR

int[] array = {1,1,2,3,4,5,6,7,8,8};

Set<Integer> set = new HashSet<Integer>();

for(int i = 0; i < array.length ; i++)
{
//If same integer is already present then add method will return FALSE
if(set.add(array[i]) == false)
{
          System.out.println("Duplicate element found : " + array[i]);
}

}

Removing white spaces

Method 1:
String s = "This is a sentence";
String s2 = s.trim();


Method 2:
String s = "This is a sentence";
String s2 = s.replaceAll("\\s", "");

Find Factorial of a number

public static int factorial(int number){
//base case
if(number == 0){
return 1;
}
return number*factorial(number -1);
}

(OR)

public static int factorial(int number){
int result = 1;
while(number != 0){
result = result*number;
number--;
}

return result;
}
}

Print Fibonacci Series

public static int fibonacci2(int number)
{
 if(number == 1 || number == 2)
{ return 1; }

 int fibo1=1, fibo2=1, fibonacci=1; 

for(int i= 3; i<= number; i++)
 fibonacci = fibo1 + fibo2;  //Fibonacci number is sum of previous two Fibonacci number 
 fibo1 = fibo2;
 fibo2 = fibonacci; 
}

 return fibonacci; //Fibonacci number 
}
}

(OR)

public static int fibonacci(int number)
{
 if(number == 1 || number == 2)
{ return 1; } 
return fibonacci(number-1) + fibonacci(number -2); //tail recursion 
}

Check if String Palindrome

We can check palindrome string by reversing string and checking whether it is equal to the original string or not.

checkIfPalindrome(String s)
{

StringBuilder s2 = new StringBuilder(s);
s2.reverse();

String rev_s2 = s2.toString();

if(s.equals(rev_s2))
{ return true; }
else
{ return false; }


}

(OR)

public class Palindrome {
public static void main(String[] args) {
String str = "OOLOO";
StringBuffer newStr =new StringBuffer();
for(int i = str.length()-1; i >= 0 ; i--) {
newStr = newStr.append(str.charAt(i));
}
if(str.equalsIgnoreCase(newStr.toString())) {
System.out.println("String is palindrome");
} else {
System.out.println("String is not palindrome");
}
}

}