Skip to main content

Posts

Showing posts with the label slicing

Program to sort the first half of an array in ascending and second half in descending order

Ex:-  [2, 4, 3, 10, 5, 8] [2, 4, 3]  and [10, 5, 8] ====>  [2, 3, 4] ascending                                                              [10, 8, 5] descending [ 2, 3, 4, 10, 8, 5] is the required answer.  Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class ArraySort{ public static void main (String[] args){ int [] arr = { 2 , 4 , 3 , 10 , 5 , 8 }; //sorting first half in ascending order for ( int i= 0 ; i<(arr. length / 2 ); i++){ for ( int j=i+ 1 ; j<(arr. length / 2 ); j++){ if (arr[i]>arr[j]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } ...

Find the longest common substring between two Strings

 Ex:-  Longest common substring or subsequence between "concatenation" and "decatenation" is "catenation". ex:-  Between "ABABC" and "BABA"  ==> "BAB" Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.util.Scanner; public class LCS{ public static void main (String []args){ Scanner sc = new Scanner(System. in ); System. out . println ( "Enter first string:" ); String str1 = sc. next (); System. out . println ( "Enter second string:" ); String str2 = sc. next (); System. out . print (longestCommonSubstring(str1, str2)); } public static String longestCommonSubstring (String str1, String str2){ for ( int i= 0 ; i<str1. length (); i++){ String temp = str1. substring (i); if (str2. contains (temp)) return temp; ...

Find all permutations of a string

 Ex:- Permutations of string "abc" are           "abc"  "acb"   "bac"  "bca"  "cab"  "cba"  Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class StrPermutation{ public static void main (String []args){ String str = "abc" ; permute(str, "" ); } public static void permute (String str, String ans){ if (str. length ()== 0 ){ System. out . print (ans+ " " ); return ; } for ( int i= 0 ; i<str. length (); i++){ char ch = str. charAt (i); String rem = str. substring ( 0 ,i) + str. substring (i+ 1 ); permute(rem, ans+ch); } } } Python def permute( str , ans): if len ( str ) == 0 : print (ans, end = " " ) return for i in range ( 0 , len ( s...