I had a question regarding a basic program I was writing said whether a word such as racecar is a palindrome or not.
All my methods which reverse the string, strip the punctuation work but the one that determines if it is a palindrome does not.
/**
* Determines if a series of letters makes a palinedrome
*
* #param str All punctuation and spaces have been removed
* before this method is called.
* #return true if phrase is a palindrome,
* false otherwise.
*/
public boolean isPalindrome(String str)
{
String d = reverseString (str);
return( str.equals (reverseString (str) ) );
}
Okay, I'm not sure what purpose d is meant to serve in your function since it's never used but, if you want to see why your function's not working, just add debug code:
public boolean isPalindrome (String str) {
System.out.println ("DEBUG: original string = '" + str + "'");
System.out.println ("DEBUG: reverse string = '" + reverseString (str) + "'");
if (str.equals (reverseString (str)))
System.out.println ("DEBUG: returning true");
else
System.out.println ("DEBUG: returning false");
return str.equals (reverseString (str));
}
I'd bet money on there being something wrong with your reverseString function (but not much money). These debug statements should give you enough to figure out where the problem lies.
If string reverseString(String string), and all whitespace was removed then checking if something is a palindrome should be
public boolean isPalindrome(String string)
{
return string.equals(reverseString(string));
}
Granted this is case sensitive so if your palindrome definition does not care about casing, then use equalsIgnoreCase instead.
If this does not work, then you may want to check your stripping and reverseString methods again.
Your problem is the reverse string method you have not shown. If that method is working properly then your isPalindrome method should work. All you need to do is fix your reverse string method.
Java does not have a native reverse string method, and I highly recommend you write your own.
Java does, however, have a reverse method for StringBuffer and StringBuilder. StringBuilder is preferred over StringBuffer.
Use the equals method to compare your reversed string to the original string
The code should be like this:
String d = reverseString (str);
return( str.equals (d) );
You don't have to call twice reverseString()
P.S.: StringBuffer has a method that reverses a String.
I'm sure you've already submitted your homework by now, but I'm learning java and needed the practice, so here's my code for you. It uses a char array and reverses that. I'd assume the best way would be to use a StringBuilder, but the intention of your homework is probably to learn to do it yourself:
public class reverseString {
public static void main(String[] args) {
System.out.println("racecar is a palindrome: "+ isPalindrome("racecar"));
}
public static boolean isPalindrome(String str)
{
String d = reverseString (str);
return( str.equals (reverseString (str) ) );
}
private static char[] reverse(char[] input) {
int length = input.length;
char[] reversed = new char[length];
for (int i=0;i<length;i++) {
reversed[length-i-1]=input[i];
}
return reversed;
}
private static String reverseString(String input){
String reversed = new String(reverse(input.toCharArray()));
return reversed;
}
}
Output:
racecar is a palindrome: true
If anyone has any comments on why my code sucks, fire away. I'd appreciate any constructive criticism.
Related
So I have to reverse a string but like an example would be reverse Hello World. Well my code reverses it like this dlroW olleH and you have to reverse it like World Hello. This is my code below can someone help me fix it or tell me what im doing wrong please. I need to do as you create a new object and input the data through the object and then call the method.
public class reverseMe {
public String reverseMe(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
}
What do you mean for "without reverse function or loops". First of all in java are called methods, not functions, and second in some way you need to iterate the strings. This code just does the job with a recursive method. Call it from your constructor and you’re done. There aren't any already built-in java methods to do what you want.
public class HelloWorld{
public String recursiveReverse(String[] words,StringBuilder b,int length){
if (length < 0)
return b.toString();
else{
b.append(words[length] + " ");
length--;
return recursiveReverse(words,b,length);
}
}
public String reverse (String input){
String[] words = input.split(" ");
StringBuilder reverse = new StringBuilder();
return recursiveReverse(words,reverse,words.length-1);
}
public static void main(String []args){
HelloWorld a = new HelloWorld();
System.out.println(a.reverse("hello this is a test reverse this string"));
}
}
Output:
string this reverse test a is this hello
This answer assumes the following:
Can't use built-in reverse() function, such as found on StringBuilder and Collections.
Can't use loops.
Input can contain any number of words.
Words are separated by a single space.
First, the easiest solution would be to split() the input and then use Stream logic to combine the words in reverse order, however I consider Stream logic to be "Loop logic", so that won't do.
That leaves the use of a recursive method as a solution, similar to the attempt in the question:
static String reverseWords(String input) {
int idx = input.indexOf(' ');
if (idx == -1)
return input;
return reverseWords(input.substring(idx + 1)) + ' ' + input.substring(0, idx);
}
Test
System.out.println(reverseWords("Hello World"));
System.out.println(reverseWords("The quick brown fox jumps over the lazy dog"));
Output
World Hello
dog lazy the over jumps fox brown quick The
We can you use code, however instead of CharAt, we can use it for loops. My method does require java.util.Arrays; to get a subset of the given array. Note, you will have to do reverseMe(str.split(" ")) to run it.
import java.util.Arrays;
public class reverseMe {
public String reverseMe(String[] s) {
if(s.length == 0)
return "";
return s[s.length - 1] + " " + reverseMe(Arrays.copyOfRange(s,0,s.length-1));
}
}
Input: "Hello Newer World"
Output: "World Newer Hello"
Since you can't use any loops or reverse methods, that would leave a recursive method.
However, this is not very efficient.
It works by repeatedly splitting on string less the last word of the previous string and then returning a new String in reversed order.
ReverseMe r = new ReverseMe();
String reversed =r.reverseMe("This is a test of reversing a string");
System.out.println(reversed);
public String reverseMe(String s) {
String arr[] = s.split("\\s+");
if (arr.length > 1) {
return arr[arr.length-1] + " " + reverseMe(s.substring(0, s.lastIndexOf(" ")));
}
return arr[arr.length-1];
}
Prints
string a reversing of test a is This
i need to get a string and rearrange it with recursion by getting char and by that char i have to move that char everywhere on the string to the end
like "Hello world!" ,'l' => "Heo word!lll"
i have problems understading the recursion way of thinking
so i started with this:
public static String ChToLast (String str, char ch){
if(str.indexOf(ch)== -1){
return str;
}else{
if(str.indexOf(0) == ch){
return str;
}
}
thank you for your help :)
Recursion is the practise of reusing your method inside itself. In this case, I will provide a solution to explain what happens:
public static String chrToLast(String str, char ch) {
//This if statement details the end condition
if(str.length() < 1) {
return "";
}
String newString = str.substring(1); //Create new string without first character
if(str.indexOf(ch) == 0) { //This happens when your character is found
return chrToLast(newString, ch) + ch;
} else { //This happens with all other characters
return str.charAt(0) + chrToLast(newString, ch);
}
}
If you execute:
chrToLast("Hello, World!", 'l')
This will result in the desired result: Heo, Word!lll
Process
In general, this method works by checking which character is currently the first in the given string, and then deciding what to do. If the first character is the same as the one your looking for (l), it will then remove that character from the string and use chrToLast on that new string. But, it also adds the character it found to the end of the result by using + ch. It continues to do this until there are no more characters left, which is what the end condition is for.
The end condition
The end condition returns an empty string "" because that is what is called the base case of the algorithm. You can think of a recursive algorithm as something solving a problem by calling itself a number of times. By calling themselves, recursive algorithms move towards a base. In this particular case, it does that by subtracting one character off the string each time the method is executed. Once there are no characters left, it reaches the base case which is "", where the string is finally empty and no characters can be subtracted anymore. (Hence it returns nothing as it's final state)
I hope this answers your question. It's important to understand this concept, as it is very powerful. Try to study the code and comment if something's not clear.
Something that can also help is by executing this code in an IDE and using the debugger to walk through its execution. You can then see for yourself what the flow of the program is, and see the value of the variables in play.
If you use recursion, it will be pretty expensive call for the result you are expecting. Lot of movement of String or charArray elements, eitherway you do. I don't see its a wiser choice. I would do it this way, it will be of space complexity O(2n) & performance complexity O(n).
public class Solve {
public static void main(String[] args) {
System.out.println(ChToLast("Hello world!", 'l'));
}
public static String ChToLast(String str, char ch) {
char[] chars = str.toCharArray();
char[] modChars = new char[chars.length];
int i = 0;
for(char element : chars){
if(ch != element){
modChars[i++] = element;
}
}
Arrays.fill(modChars, i, chars.length , ch);
return new String(modChars);
}
}
If you use while loop and write a method to check if that string means perfect statement then that may work for you
Here you would need some help of NLP concept to check everytime if arranged chars are making any statement or are grammatically correct.
This will help
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );
/**
* #(#)palindrome1.java
*
* palindrome1 application
*
* #author
* #version 1.00 2013/11/15
*/
public class palindrome1 {
static boolean isPalindrome(String str) {
int count=0;
//check all characters of sequence is palindrome
for(int i = 0; i < str.length();i++)
{
if(str.charAt(i)!=str.charAt(str.length()-1-i))
{
return false;
}
}
//if it is return true otherwise return false
return true;
}
public static void main(String[] args) {
// TODO, add your application code
String sentence= "bob gave that pop race car to me." ;
String sentenceMax="";
String sentenceNew="";
sentence = sentence.replace( " ","");
for(int i = 0;i<sentence.length();i++)
{
for(int k=0;k<i;k++)
{
sentenceNew = sentence.substring(k,i);
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
{
sentenceMax=sentenceNew;
sentenceNew="";
}
}
}
System.out.println(sentenceMax);
}
}
The question is:t should ask a sentence from user and find the longest palindrome substring in the sentence ignoring the spaces in the sentence and print the longest palindrome substring. You MUST use the function you wrote in Part B. The sentences must be case-insensitive.
and part B is the first method named isPalindrome() in mycode.
The output should be:
racecar
but my code outputs:
e
What is wrong at my code?
You have in your code :
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
And ; is at the bad place. Since it is there it treats it as a if with an empty block, so your real block {} is calculated all the time.
It should be:
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length())
You are assigning a new value to sentenceMax each iteration. Try this instead
sentenceMax += sentenceNew;
Why did you not use the StringBuffer methods ?
StringBuffer.reverse() can reverse the String
after that you can search each substring in the reverted Source string using StringBuffer.indexOf(subString).
Isnt that a much simpler approach ?
As an exercise, the code block below intends to recursively go through a string and remove all the of the "x" characters. It does that, but I would like to keep track of the newStr without passing it as a parameter in the method. Is there anyway to move it into the method body?
Thanks!
public static String deathToX(String str, String newStr) {
//look for x char
if(str.substring(0, 1).equals("x")) {
//do nothing
} else {
//add non-x char to newStr
newStr += str.charAt(0);
}
if(str.length() == 1) {
return newStr;
}
return deathToX(str.substring(1), newStr);
}
public static void main(String[] args) {
System.out.println("Return: " + deathToX("xnoxmore", ""));
}
Well, you could change the code to:
public static String deathToX(String str)
{
// Termination case
if (str.length() == 0)
{
return str;
}
// Work out whether or not we want the first character
String prefix = str.startsWith("x") ? "" : str.substring(0, 1);
// Let the recursive call handle the rest of the string, and return
// the prefix (empty string or the first character) followed by the
// x-stripped remainder.
return prefix + deathToX(str.substring(1));
}
Is that the sort of thing you were thinking of?
Of course, this is a horribly inefficient way of doing string manipulation, but I assume you're more interested in the recursive nature of things.
I would like to keep track of the newStr without passing it as a parameter in the method.
Why? Passing the intermediary result into the function is often required in functional-style recursive programming. What I do is make a function that handles the bulk of the work and accepts the accumulator, and make a wrapper function that calls the previous one with the required starter value:
private static String deathToX0(String str, String newStr) {
// the original implementation
}
public static String deathToX(String str) {
return deathToX(str, "");
}
As an aside, you might not want to use a String for the intermediate result because of the copying involved. A StringBuilder would be faster.
The short answer is yes... with recursion typically on the way down the tree you work out the bit at each level in this case blank or the current character. So the return statement should call itself recursively then at the bottom of the tree the answer you wanted is reconstructed by adding together the sections at each level.
public static String deathToX(String str){
if (!str.isEmpty()){
return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
}else{
return "";
}
}
public static void main(String[] args){
System.out.println("Return: " + deathToX("xnoxmore"));
}
In the sample above I used the shorthand if format to put it all on one line but you could expand it out. You should be able to see that the recursive function recurses on the return statement and I put in a special case for the last level. If you were to split it and put this levels answer in a local variable e.g. tmp then you would use:
return tmp + deathToX(str.substring(1));
Remember recursion means that the current execution is only paused until the lower ones finish so you can happily store info to recover on your way back up. Hope this helps :)
public class solution {
// Return the changed string
public static String removeX(String input){
if(input.equals("") || input.equals("x"))
return "";
String returnStr="";
removeX(input.substring(1));
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)=='x')
continue;
else
returnStr+=input.charAt(i);
}
return returnStr;
}
}
This is my approach. This code goes to the end of the string, if it gets X as last string, it returns ""(nothing), then it checks the whole substring for "x", if its present in the string, it will continue, else it will append rest character to that string and it goes on.
Finally returns the updated string.!
Hope this helps..!! well, this is my first contribution here :)