Java Wrtie an isSubstring Method - java

I am stuck at solving this problem. Below is what I came up with most:
Question: Write the boolean method public static boolean isSubstring(String x, String y) that takes two Strings x and y as arguments and returns true if an only if String x is a substring of String y. String x is a substring of String y if and only if all characters in x appear consecutively in y. For this problem, the only String methods you may use are length( ) and charAt( ). If you use any other String methods, you will receive no credit for this problem.
import java.util.Scanner;
public class question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter String 1:");
String String1 = input.nextLine();
System.out.print("Enter String 2:");
String String2 = input.nextLine();
if(isSubstring(String1,String2)){
System.out.println("True");
} else {
System.out.println("False");
}
}
public static boolean isSubstring(String x, String y) {
int count = 0, xIndex = 0, yIndex = 0;
boolean sub = false;
while(!sub && yIndex < y.length()){
if(y.charAt(yIndex) == x.charAt(yIndex)){
xIndex++;
count++;
} else {
if(count == x.length()){
sub = true;
}
}
yIndex++;
}
return sub;
}
}

This checks if s2 is a substring of s1.
public static boolean isSubstring(String s1, String s2){
if(s1.length()<s2.length()) return false;
if(s1.length()==s2.length()) return s1.equals(s2);
for(int i=0;i<=s1.length()-s2.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
int matchLength=1;
for(int j=1;j<s2.length();j++){
if(s1.charAt(i+j)!=s2.charAt(j)){
break;
}
matchLength++;
}
if(matchLength==s2.length()) return true;
}
}
return false;
}

You're not guarding xIndex for overflow. Guess if substring y is placed at end of x it fails. Also mind the case where x is of smaller length than x, could just return false then as optimization if you keep lengths first in local vars at start of method

public class Task_1_9 {
public static boolean isSubstring(String s1, String s2){
if (s1.length() != s2.length()) return false;
int count = 0;
int i = 0;
int j = 0;
String s3 = s2 + s2;
while (j < s3.length() && count < s1.length()){
if (s1.charAt(i) == s3.charAt(j)){
count++;
i++;
} else {
count = 0;
}
j++;
}
return count == s1.length() ? true : false;
}
public static void main(String[] args) {
System.out.println(isSubstring("waterbottle","erbottlewat"));
}
}

Related

Check whether two strings contain same characters in same order

''Given two string s and t, write a function to check if s contains all characters of t (in the same order as they are in string t).
Return true or false.
recursion not necessary.
here is the snippet of code that I am writing in java.
problem is for input: string1="st3h5irteuyarh!"
and string2="shrey"
it should return TRUE but it is returning FALSE. Why is that?''
public class Solution {
public static String getString(char x)
{
String s = String.valueOf(x);
return s;
}
public static boolean checkSequence(String s1, String s2)
{
String a = getString(s1.charAt(0));
String b = getString(s2.charAt(0));
for (int i = 1; i < s1.length(); i++)
if (s1.charAt(i) != s1.charAt(i - 1))
{
a += getString(s1.charAt(i));
}
for (int i = 1; i < s2.length(); i++)
if (s2.charAt(i) != s2.charAt(i - 1))
{
b += getString(s2.charAt(i));
}
if (!a.equals(b))
return false;
return true;
}
}
This is a solution:
public class Solution {
public static String getString(char x)
{
String s = String.valueOf(x);
return s;
}
public static boolean checkSequence(String s1, String s2)
{
String a = getString(s1.charAt(0));
String b = getString(s2.charAt(0));
int count = 0;
for (int i = 0; i < s1.length(); i++)
{
if (s1.charAt(i) == s2.charAt(count))
{
count++;
}
if (count == s2.length())
return true;
}
return false;
}
}
Each char of String s1 is compared with a char of String s2 at position count,
if they match count increases: count++;
If count has the length of String 2 all chars matched and true is returned.
there are two problems i can see in that code
1 for (int i = 1; i < s1.length(); i++) you are starting from index 1 but string indexes starts from 0
2 if (s1.charAt(i) != s1.charAt(i - 1)) here you are comparing characters of same strings s1 in other loop also this is the case
please fix these first, then ask again
this could be what you are searching for
public class Solution {
public static boolean checkSequence(String s1, String s2) {
for(char c : s2.toCharArray()) {
if(!s1.contains(c+"")) {
return false;
}
int pos = s1.indexOf(c);
s1 = s1.substring(pos);
}
return true;
}
}
Your approach to solve this problem can be something like this :
Find the smaller string.
Initialise the pointer to starting position of smaller string.
Iterate over the larger string in for loop and keep checking if character is matching.
On match increase the counter of smaller pointer.
while iterating keep checking if smaller pointer has reached to end or not. If yes then return true.
Something like this :
public static boolean checkSequence(String s1, String s2)
{
String smallerString = s1.length()<=s2.length() ? s1 : s2;
String largerString = smallerString.equals(s2) ? s1 : s2;
int smallerStringPointer=0;
for(int i=0;i<largerString.length();i++){
if(smallerString.charAt(smallerStringPointer) == largerString.charAt(i)){
smallerStringPointer++;
}
if(smallerStringPointer == smallerString.length()){
return true;
}
}
return false;
}
public static boolean usingLoops(String str1, String str2) {
int index = -10;
int flag = 0;
for (int i = 0; i < str1.length(); i++) {
flag = 0;
for (int j = i; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if (j < index) {
return false;
}
index = j;
flag = 1;
break;
}
}
if (flag == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str1 = s.nextLine();
String str2 = s.nextLine();
// using loop to solve the problem
System.out.println(usingLoops(str1, str2));
s.close();
}

Compare two String using recursion (case insensitive)

I needed to Write a recursive method to compare two Strings using alphabetical order without using compareTo.
string1 comes before string2 returns an integer less than 0
string1 == (or indistinguishable from) string2 returns 0
string1 comes after string2 returns an integer greater than 0
I have written a method that works just fine, the problem is that if I compare two similar string or a string to itself it returns 1 instead of 0.
Any idea how can I optimize my method so it is not too long and does not fail to compare two identical strings?
I think part of my problem is because I declared my variable static, but not sure how I should work it out to declare them inside the method.
Code:
public class test{
public static String s1 = "alpha";
public static String s2 = "delta";
public static String s3 = "omega";
public static String s4 = "alpha";
public static int result;
public static void main (String[]args){
System.out.println(recursiveCompare(s1,s2)); // -1 good
System.out.println(recursiveCompare(s3,s1)); // 1 good
System.out.println(recursiveCompare(s4,s1)); // 1 FAIL!!! should be 0
System.out.println(recursiveCompare(s2,s3)); // -1 good
System.out.println(recursiveCompare(s1,s1)); // -1 FAIL!!! should be 0
}
public static int recursiveCompare(String s1, String S2){
if (s1.length() ==0 || s2.length()==0){
if ((s1.length() ==0 && s2.length()==0)){result = 0;}
else if ((s1.length() !=0 || s2.length()==0)){result = 1;}
else if ((s1.length() ==0 || s2.length()!=0)){result = -1;}
}
else
{
recursiveCompareHelper(s1, s2,0);
}
return result;
}
public static int recursiveCompareHelper(String s1,String s2, int index){
try{
if (s1.regionMatches(true,index,s2,index,1)){
result = recursiveCompareHelper(s1,s2,(index+1));}
else {
if (s1.charAt(index) > s2.charAt(index)){
result =1;
}
else if (s1.charAt(index) < s2.charAt(index)){
result =-1;
}
else if (s1.charAt(index) == s2.charAt(index)){
result = recursiveCompareHelper(s1,s2,(index+1));
}
}
} catch (StringIndexOutOfBoundsException e){
if (s1.charAt(index)==0 && s2.charAt(index)== 0){result = 0;}
else if (s1.charAt(index)==0 && s2.charAt(index)!= 0){result = 1;}
else if (s1.charAt(index)!=0 && s2.charAt(index)== 0){result =-1;}
}
return result;
}
}
first of all, notice you pass S2 as a parameter to recursiveCompare, not s2,
so actually you compare everything with "delta" because s2 is a static variable.
second of all, when comparing strings, as soon as you find a difference you can return an answer, its wrong just to change the value of result because it can be changed again later and return a wrong answer.
this is my solution, inside each recursive call I compare between the first letters and
if they're equal, I call the function recursively without the first letters of the strings
public class test {
public static String s1 = "alpha";
public static String s2 = "delta";
public static String s3 = "omega";
public static String s4 = "alpha";
public static void main(String[] args) {
System.out.println(recursiveCompare(s1, s2)); // -1 good
System.out.println(recursiveCompare(s3, s1)); // 1 good
System.out.println(recursiveCompare(s4, s1)); // 1 FAIL!!! should be 0
System.out.println(recursiveCompare(s2, s3)); // -1 good
System.out.println(recursiveCompare(s1, s1)); // -1 FAIL!!! should be 0
}
public static int recursiveCompare(String s1, String s2) {
if (s1.length() == 0 || s2.length() == 0) {
if ((s1.length() == 0 && s2.length() == 0)) {
return 0;
} else if (s1.length() != 0) {
return 1;
} else {
return -1;
}
}
if (s1.charAt(0) < s2.charAt(0)) {
return -1;
} else if (s1.charAt(0) > s2.charAt(0)) {
return 1;
} else if (s1.charAt(0) == s2.charAt(0)) {
return 0;
} else {
return recursiveCompare(s1.substring(1), s2.substring(1));
}
}
}
output:
-1
1
0
-1
0
You do not need to use the .langth() method. To compare strings, you need to use .equals()
public static int recursiveCompare(String s1, String s2){
if (s1.equals(s2)) {
return 0;
}
else
{
recursiveCompareHelper(s1, s2,0);
}
return result;
}
And in recursiveCompare(String s1, String S2) you hava S2 insted of s2.
Main mistake that you have done in your program is in function recursiveCompare you have taken argument as S2 and in a function using variable s2 which is declared as static variable so your function is failing to give correct result. Remember java is case sensitive language and in that case S2 is not same as s2.
below is the program which i have modified use that for your understanding.
public class Test{
/* public static String s1 = "alpha";
public static String s2 = "delta";
public static String s3 = "omega";
public static String s4 = "alpha";*/
public static int result;
public static void main (String[]args){
String s1 = "alpha";
String s2 = "delta";
String s3 = "omega";
String s4 = "alpha";
System.out.println(recursiveCompare(s1,s2)); // -1 good
System.out.println(recursiveCompare(s3,s1)); // 1 good
System.out.println(recursiveCompare(s4,s1)); // 1 FAIL!!! should be 0
System.out.println(recursiveCompare(s2,s3)); // -1 good
System.out.println(recursiveCompare(s1,s1)); // -1 FAIL!!! should be 0
}
public static int recursiveCompare(String s1, String S2){
if (s1.length() ==0 || S2.length()==0){ // here you have to use S2 and not s1
if ((s1.length() ==0 && S2.length()==0)){result = 0;}
else if ((s1.length() !=0 || S2.length()==0)){result = 1;}
else if ((s1.length() ==0 || S2.length()!=0)){result = -1;}
}
else
{
recursiveCompareHelper(s1, S2,0);
}
return result;
}
public static int recursiveCompareHelper(String s1,String s2, int index){
// System.out.println("String are" + s1+" "+ s2 + " index is "+ index);
if(index<s1.length()) {
// System.out.println("Characters at index : "+ s1.charAt(index)+ " "+ s2.charAt(index));
if (s1.charAt(index) > s2.charAt(index)){
//System.out.println("In the if condition");
result= 1;
}
else if (s1.charAt(index) < s2.charAt(index)){
//System.out.println("In the else if condition");
result =-1;
}
else if (s1.charAt(index) == s2.charAt(index)){
//System.out.println("Character at "+index);
result = recursiveCompareHelper(s1,s2,(index+1));
}
}
else return 0;
return result;
}
}

JAVA DFS does not print out required line

I am programming a DFS problem in java over the n-puzzle problem. I have the following code :
public class Dfssolution
{
public static int cost=0;
public static String goal;
public static int n=3;
public static HashSet<String> closedlist= new HashSet<String>();
public static boolean solved = false;
public static String current;
public static int spc;
public static String temp;
public static LinkedHashSet<String> openlist = new LinkedHashSet<String>();
public Dfssolution()
{
}
public static void main(String args []){
String start= "103256789";
goal = "130256789";
String temp;
openlist.add(start);
while (openlist.isEmpty() == false && solved == false){
current= openlist.iterator().next();
openlist.remove(current);
cost++;
if(current.equals(goal)){
System.out.println(cost);
solved=true;
break;
}
else{
closedlist.add(current);
if(checkRight(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= right(current);
openlist.add(temp);
}
if(checkUp(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= up(current);
openlist.add(temp);
}
if(checkDown(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= down(current);
openlist.add(temp);
}
if(checkLeft(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= left(current);
openlist.add(temp);
}
}
}
}
public static String left(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc-1];
x[spc-1] = a;
tem= new String(x);
return tem;
}
public static String right(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc+1];
x[spc+1] = a;
tem= new String(x);
return tem;
}
public static String up(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc-n];
x[spc-n] = a;
tem= new String(x);
return tem;
}
public static String down(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc+n];
x[spc+n] = a;
tem= new String(x);
return tem;
}
public static boolean checkUp(String s){
spc=s.indexOf("0");
if(spc > n-1){
return true;
}
else{
return false;
}
}
public static boolean checkDown(String s){
spc=s.indexOf("0");
if(spc < n*(n-1)){
return true;
}
else{
return false;
}
}
public static boolean checkLeft(String s){
spc=s.indexOf("0");
if(spc !=0 &&(spc % n) !=0){
return true;
}
else{
return false;
}
}
public static boolean checkRight(String s){
spc=s.indexOf("0");
if(spc !=n-1 && spc % n !=n-1){
return true;
}
else{
return false;
}
}
}
I am testing it out to see if it will return the number of nodes expanded(known as 'cost') to reach the goal state in the code. I tested it on a simple problem which is
103
256
789
as the start state and
130
256
789
as the goal state
The program does not print out the cost (number of nodes expanded) which should be 2.
Note that n represents 3 in a 3x3 puzzle problem
You need to move statement closedlist.add(current); to the end of else block. Otherwise, every condition checks if closedlist contains current (and it does, you just put it here), and nothing will be put in openlist.
After this changes solution is found in 2 steps, but there is another mistake to work on — you're counting cost globally, while it should be counted separately for each branch if you want to find minimal amount of moves.

Get index of first occurrance of second string in the first String using recursion

public int indexOf(String s1,String s2){
if(s1.length()<s2.length())
return -1;
else if(s1.substring(s1.length()-s2.length()).equals(s2))
return s1.length()-s2.length();
else
return indexOf(s1.substring(0,s1.length()-1),s2);
}
I wrote this method to get index of the second string in the first one
but it has a bug it cant effectively return first occurrence of the second string this is because I am using logic to find the second string from backwards and I could not think of any other logic. Any suggestions would be appreciated.
example of a failure case: firstString "BarackObama" second string "a"
As you noted, you are doing it backwards. Instead, you should go forward:
public static int indexOf(String s1, String s2){
if(s1.length()<s2.length()) {
return -1;
}
else if(s1.substring(0, s2.length()).equals(s2)) {
return 0;
}
else {
int i = indexOf(s1.substring(1, s1.length()), s2);
if (i == -1) {
return i;
} else {
return 1 + i;
}
}
}
Example:
String s1 = "BarackObama";
String s2 = "rac";
indexOf(s1, s2);
It would run like this:
indexOf("BarackObama", "rac"):
"BarackObama".substring(0, 3).equals("rac") -> false
return 1 + indexOf("BarackObama".substring(1, 11), "rac")
indexOf("arackObama", "rac"):
"arackObama".substring(0, 3).equals("rac") -> false
return 1 + indexOf("arackObama".substring(1, 10), "rac")
indexOf("rackObama", "rac"):
"rackObama".substring(0, 3).equals("rac") -> true
return 0;
return 0 + 1 + 1 = 2
I think the way you are using subString(int startIndex), it would give you characters from the end. If you pass only on parameter to the subString method, it acts as the start index for the subString it returns. So in case your example, you would get the "a" at the end of "BarackObama". You can try to use substring(int beginIndex, int endIndex).
Here it is.
private int indexOf(String s1,String s2){
int index=0;
if( s1 ==null || s2 ==null){
return -1;
}else if(s1.length()<s2.length()){
return -1;
}else{
index=s1.lastIndexOf(s2);
s1=s1.substring(0,index);
if(!s1.contains(s2)){
return index;
}else{
return indexOf(s1,s2);
}
}
}
public int indexOf(String s1, String s2){
if (s1.length() < s2.length()){
return -1;
} else {
int n = 0;
int index = findIndex(s1, s2, n);
return index;
}
}
private int findIndex(String s1, String s2, int n){
if (s1.substring(n, (n + s2.length())).equals(s2)){
return n;
} else if ((n < s1.length() - s2.length())){
return findIndex(s1, s2, (n + 1));
} else{
return -1;
}
}

Creating a recursive method for Palindrome

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:
public static void main (String[] args){
System.out.println(isPalindrome("noon"));
System.out.println(isPalindrome("Madam I'm Adam"));
System.out.println(isPalindrome("A man, a plan, a canal, Panama"));
System.out.println(isPalindrome("A Toyota"));
System.out.println(isPalindrome("Not a Palindrome"));
System.out.println(isPalindrome("asdfghfdsa"));
}
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() == 1 ) return true;
in= in.toUpperCase();
if(Character.isLetter(in.charAt(0))
}
public static boolean isPalindromeHelper(String in){
if(in.equals("") || in.length()==1){
return true;
}
}
}
Can anyone supply a solution to my problem?
Here I am pasting code for you:
But, I would strongly suggest you to know how it works,
from your question , you are totally unreadable.
Try understanding this code. Read the comments from code
import java.util.Scanner;
public class Palindromes
{
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
// if length =0 OR 1 then it is
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
// check for first and last char of String:
// if they are same then do the same thing for a substring
// with first and last char removed. and carry on this
// until you string completes or condition fails
return isPal(s.substring(1, s.length()-1));
// if its not the case than string is not.
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("type a word to check if its a palindrome or not");
String x = sc.nextLine();
if(isPal(x))
System.out.println(x + " is a palindrome");
else
System.out.println(x + " is not a palindrome");
}
}
Well:
It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
In the first method, why are you testing for testing for a single space or any single character?
You might want to consider generalizing your termination condition to "if the length is less than two"
Consider how you want to recurse. One option:
Check that the first letter is equal to the last letter. If not, return false
Now take a substring to effectively remove the first and last letters, and recurse
Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.
I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() < 2 ) return true;
if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
return isPalindrome(in.substring(1,in.length-2));
else
return false;
}
Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.
I think, recursion isn't the best way to solve this problem, but one recursive way I see here is shown below:
String str = prepareString(originalString); //make upper case, remove some characters
isPalindrome(str);
public boolean isPalindrome(String str) {
return str.length() == 1 || isPalindrome(str, 0);
}
private boolean isPalindrome(String str, int i) {
if (i > str.length / 2) {
return true;
}
if (!str.charAt(i).equals(str.charAt(str.length() - 1 - i))) {
return false;
}
return isPalindrome(str, i+1);
}
Here is my go at it:
public class Test {
public static boolean isPalindrome(String s) {
return s.length() <= 1 ||
(s.charAt(0) == s.charAt(s.length() - 1) &&
isPalindrome(s.substring(1, s.length() - 1)));
}
public static boolean isPalindromeForgiving(String s) {
return isPalindrome(s.toLowerCase().replaceAll("[\\s\\pP]", ""));
}
public static void main(String[] args) {
// True (odd length)
System.out.println(isPalindrome("asdfghgfdsa"));
// True (even length)
System.out.println(isPalindrome("asdfggfdsa"));
// False
System.out.println(isPalindrome("not palindrome"));
// True (but very forgiving :)
System.out.println(isPalindromeForgiving("madam I'm Adam"));
}
}
public class palin
{
static boolean isPalin(String s, int i, int j)
{
boolean b=true;
if(s.charAt(i)==s.charAt(j))
{
if(i<=j)
isPalin(s,(i+1),(j-1));
}
else
{
b=false;
}
return b;
}
public static void main()
{
String s1="madam";
if(isPalin(s1, 0, s1.length()-1)==true)
System.out.println(s1+" is palindrome");
else
System.out.println(s1+" is not palindrome");
}
}
Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:
private static boolean isPalindrome(String str, int left, int right) {
if(left >= right) {
return true;
}
else {
if(str.charAt(left) == str.charAt(right)) {
return isPalindrome(str, ++left, --right);
}
else {
return false;
}
}
}
public static void main(String []args){
String str = "abcdcbb";
System.out.println(isPalindrome(str, 0, str.length()-1));
}
Here are three simple implementations, first the oneliner:
public static boolean oneLinerPalin(String str){
return str.equals(new StringBuffer(str).reverse().toString());
}
This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:
public static boolean isPalindrome(String str){
if(str.isEmpty()) return true;
int last = str.length() - 1;
for(int i = 0; i <= last / 2;i++)
if(str.charAt(i) != str.charAt(last - i))
return false;
return true;
}
And recursively:
public static boolean recursivePalin(String str){
return check(str, 0, str.length() - 1);
}
private static boolean check (String str,int start,int stop){
return stop - start < 2 ||
str.charAt(start) == str.charAt(stop) &&
check(str, start + 1, stop - 1);
}
public static boolean isPalindrome(String str)
{
int len = str.length();
int i, j;
j = len - 1;
for (i = 0; i <= (len - 1)/2; i++)
{
if (str.charAt(i) != str.charAt(j))
return false;
j--;
}
return true;
}
Try this:
package javaapplicationtest;
public class Main {
public static void main(String[] args) {
String source = "mango";
boolean isPalindrome = true;
//looping through the string and checking char by char from reverse
for(int loop = 0; loop < source.length(); loop++){
if( source.charAt(loop) != source.charAt(source.length()-loop-1)){
isPalindrome = false;
break;
}
}
if(isPalindrome == false){
System.out.println("Not a palindrome");
}
else
System.out.println("Pailndrome");
}
}
String source = "liril";
StringBuffer sb = new StringBuffer(source);
String r = sb.reverse().toString();
if (source.equals(r)) {
System.out.println("Palindrome ...");
} else {
System.out.println("Not a palindrome...");
}
public class chkPalindrome{
public static String isPalindrome(String pal){
if(pal.length() == 1){
return pal;
}
else{
String tmp= "";
tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));
return tmp;
}
}
public static void main(String []args){
chkPalindrome hwObj = new chkPalindrome();
String palind = "MADAM";
String retVal= hwObj.isPalindrome(palind);
if(retVal.equals(palind))
System.out.println(palind+" is Palindrome");
else
System.out.println(palind+" is Not Palindrome");
}
}
Here is a recursive method that will ignore specified characters:
public static boolean isPal(String rest, String ignore) {
int rLen = rest.length();
if (rLen < 2)
return true;
char first = rest.charAt(0)
char last = rest.charAt(rLen-1);
boolean skip = ignore.indexOf(first) != -1 || ignore.indexOf(last) != -1;
return skip || first == last && isPal(rest.substring(1, rLen-1), ignore);
}
Use it like this:
isPal("Madam I'm Adam".toLowerCase(), " ,'");
isPal("A man, a plan, a canal, Panama".toLowerCase(), " ,'");
It does not make sense to include case insensitivity in the recursive method since it only needs to be done once, unless you are not allowed to use the .toLowerCase() method.
there's no code smaller than this:
public static boolean palindrome(String x){
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
if you want to check something:
public static boolean palindrome(String x){
if(x==null || x.length()==0){
throw new IllegalArgumentException("Not a valid string.");
}
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
LOL B-]
public static boolean isPalindrome(String p)
{
if(p.length() == 0 || p.length() == 1)
// if length =0 OR 1 then it is
return true;
if(p.substring(0,1).equalsIgnoreCase(p.substring(p.length()-1)))
return isPalindrome(p.substring(1, p.length()-1));
return false;
}
This solution is not case sensitive. Hence, for example, if you have the following word : "adinida", then you will get true if you do "Adninida" or "adninida" or "adinidA", which is what we want.
I like #JigarJoshi answer, but the only problem with his approach is that it will give you false for words which contains caps.
Palindrome example:
static boolean isPalindrome(String sentence) {
/*If the length of the string is 0 or 1(no more string to check),
*return true, as the base case. Then compare to see if the first
*and last letters are equal, by cutting off the first and last
*letters each time the function is recursively called.*/
int length = sentence.length();
if (length >= 1)
return true;
else {
char first = Character.toLowerCase(sentence.charAt(0));
char last = Character.toLowerCase(sentence.charAt(length-1));
if (Character.isLetter(first) && Character.isLetter(last)) {
if (first == last) {
String shorter = sentence.substring(1, length-1);
return isPalindrome(shorter);
} else {
return false;
}
} else if (!Character.isLetter(last)) {
String shorter = sentence.substring(0, length-1);
return isPalindrome(shorter);
} else {
String shorter = sentence.substring(1);
return isPalindrome(shorter);
}
}
}
Called by:
System.out.println(r.isPalindrome("Madam, I'm Adam"));
Will print true if palindrome, will print false if not.
If the length of the string is 0 or 1(no more string to check), return true, as the base case. This base case will be referred to by function call right before this. Then compare to see if the first and last letters are equal, by cutting off the first and last letters each time the function is recursively called.
Here is the code for palindrome check without creating many strings
public static boolean isPalindrome(String str){
return isPalindrome(str,0,str.length()-1);
}
public static boolean isPalindrome(String str, int start, int end){
if(start >= end)
return true;
else
return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}
public class PlaindromeNumbers {
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
/**
* Function to check a String is palindrome or not
* #param s input String
* #return true if Palindrome
*/
public boolean checkPalindrome(String s) {
if (s.length() == 1 || s.isEmpty())
return true;
boolean palindrome = checkPalindrome(s.substring(1, s.length() - 1));
return palindrome && s.charAt(0) == s.charAt(s.length() - 1);
}
Simple Solution
2 Scenario --(Odd or Even length String)
Base condition& Algo recursive(ch, i, j)
i==j //even len
if i< j recurve call (ch, i +1,j-1)
else return ch[i] ==ch[j]// Extra base condition for old length
public class HelloWorld {
static boolean ispalindrome(char ch[], int i, int j) {
if (i == j) return true;
if (i < j) {
if (ch[i] != ch[j])
return false;
else
return ispalindrome(ch, i + 1, j - 1);
}
if (ch[i] != ch[j])
return false;
else
return true;
}
public static void main(String[] args) {
System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));
}
}
for you to achieve that, you not only need to know how recursion works but you also need to understand the String method.
here is a sample code that I used to achieve it: -
class PalindromeRecursive {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String input=sc.next();
System.out.println("is "+ input + "a palindrome : " + isPalindrome(input));
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
isPalindrome(s.substring(low++,high--));
}
return true;
}
}

Categories

Resources