Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false.
Examples:
Input: str = abcdefba, X = 2
Output: true
Explanation:
First 2 characters of both string str and reversed string str are same.Input: str = GeeksforGeeks, X = 3
Output: false
Approach: This problem can be solved by iterating over the characters of the string str. Follow the steps below to solve this problem:
- Initialize two variables say, i as 0 and n as length of str to store position of current character and length of the string str respectively.
- Iterate while i less than n and x:
- If ith character from starting and ith from the last are not equal, then print false and return.
- After completing the above steps, print true as the answer.
Below is the implementation of the above approach :
C++
|
false
Time complexity: O(min(n, k))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment