This is the question:
Write a recursive method that removes all consecutively occurring letters from a string of fixed size. E.g. “AAAbbCCCC” becomes “AbC”
My Code:
public static String NoRepeats(String n, int start) {
String x = "";
if(start == n.length()-1) {
return x;
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+1);
}
else {
x += n.charAt(start);
return NoRepeats(n,start+=1);
}
}
ok, so I wasn't sure why it would only return an empty string, So I fiddled around with the syntax.
FYI String n = "AAAABBBBCCCCDDDD"
In my recursive steps I couldn't use 'start ++ or start +1", it only worked when it was 'start +=1'. This will correct it.
This is my new code:
public static String NoRepeats(String n, int start) {
String x = "";
if(start == (n.length()-1)) {
x += n.charAt(start);
return x;
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+=1);
}
else {
x += n.charAt(start);
return x +NoRepeats(n,start+=1);
}
}
I was wondering why did the above returned empty string so I went and modify your codes to see how it's done.
String a = "";
String b = "";
try {
a = Tesst1.NoRepeats("AAAbbCCCC", 0, b);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(a);
}
public static String NoRepeats(String n, int start, String b) {
if(start == n.length()-1) {
return b += n.charAt(start - 1);
}
if(n.charAt(start) == n.charAt(start+1)) {
return NoRepeats(n, start+1, b);
}
else {
b += n.charAt(start);
return NoRepeats(n,start+1, b);
}
}
This should now yield AbC.
In your code x is local to function. So, with every call you lose the value of x. Also, there was little mistake in first statement.
In classic way, you could use the result of function:
public static String noRepeats(String n, int start) {
return (start == n.length() - 1) ? "" + n.charAt(start) :
(n.charAt(start) == n.charAt(start + 1)) ? noRepeats(n, start + 1) :
n.charAt(start) + noRepeats(n, start + 1);
public static void main(String[] args) {
System.out.println(noRepeats("AAAbbCCCC", 0));
}
Or need some buffer to accumulate new characters:
public static String noRepeats(String n) {
return noRepeats(n, new StringBuilder(), 0);
}
public static String noRepeats(String n, StringBuilder result, int start) {
if(start == n.length() - 1) {
return result.append(n.charAt(start)).toString();
}
if(n.charAt(start) == n.charAt(start + 1)) {
return noRepeats(n, result, start + 1);
}
else {
result.append(n.charAt(start));
return noRepeats(n, result, start + 1);
}
}
public static void main(String[] args) {
System.out.println(noRepeats("AAAbbCCCC"));
}
I'm trying to code this one up,but I don't get an expected result:
Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string.
countX("xxhixx") → 4
countX("xhixhix") → 3
countX("hi") → 0
Here is my method:
public int countX(String str) {
int count = 0;
if(str.length() >= 1 ) {
if(str.substring(0, 1).equals("x")) {
str = str.substring(1, str.length());
count = count + 1 + countX(str);
}
}
else {
str = str.substring(1, str.length());
count = count + countX(str);
}
return count;
}
You had the right idea, but I think you over complicated things. Just check explicitly if the first character is x (as you have), and only increment count in that case. Regardless of whether it was or wasn't, continue recursing on:
public static int countX(String str) {
int count = 0;
if (str.length() > 0) {
if (str.substring(0, 1).equals("x")) {
++count;
}
str = str.substring(1, str.length());
count += countX(str);
}
return count;
}
Suppose you have a string "axbxcx". The code below looks only at the first character in the string and determines if it is an x. If so, then return 1 in addition to the number of x's found in the rest of the string. If the first character is not an x, then the number of x's in the string is equal to the number of x's in the string not including the first character, so that is what is returned.
int count(String s)
{
if (s.length() == 0) // base case
{
return 0;
}
if (s.charAt(0) == 'x')
{
return 1 + count(s.substring(1));
}
else
{
return count(s.substring(1));
}
}
How about this?
public static int countX(String str) {
if (str.length() == 0) {
return 0;
}
if (str.substring(0, 1).equals("x")) {
return 1 + countX(str.substring(1));
}
return countX(str.substring(1));
}
You should try this (it assumes you are testing outside the method that initial str value is not null and has a length greater than 0).
public int countX(String str) {
if ( str.length() == 1 ) {
return ("x".equalsTo(str) ? 1 : 0);
} else {
return (str.charAt(0) =='x' ? 1 : 0) + countX(str.substring(1,str.length())
}
}
Here is a simple way to do it.
First, check if the string is empty. This is the terminating condition of the recursion.
Then your result is simply the count for the first character (1 or 0), added to the count for the rest of the string (calculated by calling your function on substring(1)).
public static int countX(String str) {
if (str.isEmpty()) {
return 0;
}
return (str.charAt(0)=='x' ? 1 : 0) + countX(str.substring(1));
}
you can try this one:
public int countX(String str) {
int end = str.length(); //get length of the string
int counter = 0;
if(str.length()==0){
return counter; //recursion will stop here
}else{
if(str.charAt(end-1) == 'x'){
counter++;
}
end--;
str=str.substring(0,end); //your string will perform a decrease in length and the last char will be removed
}
return counter+countX(str);
}
EDIT: Really sorry, I mean Java! As for what I think, I would say the first contains if statement is for s == null or length 0, but I'm confused as to what to put in the
return spaceCount(s.substring(1, ......)) + ......;
part.
I'm trying to use some if statements to write a function that takes a string as a parameter and recursively coutns the number of blanks spaces " " it has. So far I have
public static int spaceCount (string s) {
if ( ...... ) {
return 0;
}
char c = s.charAt(0);
if (....... ) {
return spaceCount (.....);
} else {
return spaceCount(s.substring(1, ......)) + ......;
}
}
So in the first if statement, should I write the case of the string having zero length? I'm pretty sure that won't cover the case of no spaces at all, so I'm not sure how to proceed.
For the second and third, I know I have to scan the string for spaces, but I am not really sure how to do that either. Any hints or direction would be appreciated!
public static int spaceCount(final String s) {
if(s == null || s.length() == 0) {
return 0;
}
char c = s.charAt(0);
if(' ' != c) {
return spaceCount(s.substring(1));
} else {
return spaceCount(s.substring(1)) + 1;
}
}
You don't have to "scan the string for spaces", that's what the recursion passing the remainder of the string does.
s.length() - s.replaceAll(" ", "").length() returns you number of spaces.
how to count the spaces in a java string? has the answer. Probably it may help. the above line is the simplest.
[You didn't specify a programming language] Here is a solution in Java:
public static int spaceCount(String s)
{ return scRecursive (s, s.length, 0, 0); }
public static int scRecursive (String s, int len, int dex, int count)
{ if (len == dex) return count;
else
return scRecursive (s, len, dex + 1,
(' ' == s.charAt(dex) ? count + 1 : count)); }
This is tail recursive (which might imply some efficiency) and, more importantly, this does not copy/allocate substrings
Here is one in Scheme:
(define (space-count string)
(let ((length (string-length string)))
(let stepping ((index 0) (count 0)
(if (= index length)
count
(let ((char (string-ref string index)))
(stepping (+ index 1)
(if (equal? #\space char)
(+ 1 count)
count)))))))
The recursion is in the call to stepping which has two arguments - the current index and the current count of spaces. The recursion terminates when the index equals the length. The count is incremented when the current char is a space.
public class CountSpaces {
public static void main(String[] args) {
String str = " A ";
System.out.println(spaceCount(str, 0));
System.out.println(spaceCount(str));
}
public static int spaceCount(String str, int count) {
if (str == null) {
return 0;
} else if (str.length() > 0) {
char c = str.charAt(0);
if (Character.isWhitespace(c)) {
count++;
}
return spaceCount(str.substring(1), count);
} else {
return count;
}
}
public static int spaceCount(String s) {
if (s.length() == 0 || s == null) {
return 0;
}
char c = s.charAt(0);
if (!Character.isWhitespace(c)) {
return spaceCount(s.substring(1));
} else {
return spaceCount(s.substring(1, s.length())) + 1;
}
}
}
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;
}
}