Skip to main content

Posts

Showing posts with the label substring

Longest Palindromic Substring

 Ex:- If the given string is "codedoh" Output:-  "odedo" is the longest palindromic substring Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public String longestPalindrome (String s) { if (s == null || s. length () < 1 ) return "" ; int start = 0 , end = 0 ; for ( int i = 0 ; i < s. length (); i++) { int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, i + 1 ); int len = Math. max (len1, len2); if (len > end - start) { start = i - (len - 1 ) / 2 ; end = i + len / 2 ; } } return s. substring (start, end + 1 ); } private int expandAroundCenter (String s, int left, int right) { int L = left, R = right; while (L >= 0 && R < s. length () && s. charAt (L) == s. charAt (R)) { ...

Print all possible rotations of a string

 Ex:- "code" ==>   "code"  "odec"  "deco"  "ecod"          "heist"  ==>   "heist"  "eisth"  "isthe"  "sthei"  "theis" Java 1 2 3 4 5 6 7 8 9 public class Rotation{ public static void main (String[] args){ String str = "codeheist" ; for ( int i= 0 ; i<str. length (); i++){ String ans = str. substring (i,str. length ()) + str. substring ( 0 ,i); System. out . println (ans); } } } Python input_str = "codeheist" for i in range ( 0 , len (input_str)): print ( input_str [ i : len (input_str) ] + input_str [ 0 : i ] )

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; ...