I'm trying to build a palindrome. I think I might be overthinking the solution with way too many conditional loops inside my if statement. I'm having trouble trying to update the while loop to check whether it has gone through and checked for equality throughout each character of the string, and to update it. Can someone point me in the right direction, and also how can I do a cleaner job with code?
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.isPalindrome("saippuakivikauppias");
main.isPalindrome("Hello World");
main.isPalindrome("Was it a car or a cat I saw");
}
private boolean isPalindrome(String word) {
int first = word.charAt(0);
int last = word.charAt(word.length() - 1);
if(word.length() <= 1) {
return true;
} else if(word.trim().length() > 1) {
if(Character.isLetter(first) && Character.isLetter(last)) {
while(first == last) {
first++;
last--;
//if loop to check if the while loop as gone through the entire string?
//update?
}
} else {
return false;
}
}
return false;
}
}
You really overthought this one - you should think a bit more basic about your problem:
A palindrome is a string that is the same read backward and forward -> create a reverse of word and compare to word
public static boolean isPalindrome(String word){
StringBuilder reverse = new StringBuilder(word).reverse();
return word.equals(reverse.toString());
}
You could even do this - depending on your coding style - in one line.
Related
Problem Statement is from hackerrank.
Name: Simple text Editor
Description: I has taken a stackNode.in stackNode i used three variables top is for previous operation performed operate is k and s for storing the string which was either deleted or appended in previous operation.
Link to the problem
: https://www.hackerrank.com/challenges/simple-text-editor/problem?isFullScreen=false
import java.io.*;
import java.util.*;
class StackNode
{
int top;
int operat;
String s;
}
public class Solution
{
static String S="";
static Stack<StackNode> stack=new Stack<>();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0)
{
int operation=sc.nextInt();
if(operation == 1)
{
String st=sc.next();
S=S+st;
StackNode node=new StackNode();
node.top=operation;
node.s=st;
stack.push(node);
}
else
if(operation == 2)
{
int k=sc.nextInt();
delete(k,operation);
}
else
if(operation == 3)
{
int k=sc.nextInt();
print(k);
}
else
if(operation == 4)
undo();
}
}
static void delete(int k,int operation)
{
StackNode node=new StackNode();
node.top=operation;
node.operat=k;
if(S.length() < k)
{
node.s=S;
S="";
return;
}
else
{
node.s=S.substring(S.length()-k);
S=S.substring(0,S.length()-k);
}
stack.push(node);
}
static void print(int k)
{
if(k<=S.length())
System.out.println(S.charAt(k-1));
}
static void undo()
{
if(stack.isEmpty())
return;
StackNode node=stack.pop();
if(node.top == 1)
{
S=S.substring(0,S.length()-node.s.length());
}
else
if(node.top == 2)
{
S=S+node.s;
}
}
}
Problem: Copying the entire editor content on each append and each delete operation takes a long time when the string is long. Solution: Instead of keeping the editor content in a String use a StringBuffer or StringBuilder.
The content of the editor may be up to a million chars. Each of the following code lines copies this content into a new String:
S=S+st;
S=S.substring(0,S.length()-k);
S=S.substring(0,S.length()-node.s.length());
S=S+node.s;
When instead you append to or delete from a StringBuffer or StringBuilder, the characters not involved in the operation can stay in place.
Other possible slight optimizations:
On the undo stack don’t store the appended string but only the length of it. The length suffices for undoing the append operation.
Use a switch statement for selecting the right operation rather than chained if-else.
is there any difference between switch and chained if-else in terms of
time complexity and space complexity
In most cases switch on an int value should be faster than chained if-else.
Documentation link: StringBuilder
Hi I'm a complete newbie on programming and I try to search for a certain String in an array. When it's found the method should return the index but if the String is not found it should return -1.
public int poitionOfWord(String testWord) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i].equals(testWord)) {
return i;
}
}
return -1;
}
would this method return always -1 or would it actually terminate when finding a word and would return i.
Your method is correct and it will return the index in case it finds a match else if it doesn't find the match, it will come out of loop and return -1.
Just to make code crisp and concise, you can use something like this,
public static String[] wordArray = new String[]{"a", "b"};
public static int poitionOfWord(String testWord) {
return Arrays.asList(wordArray).indexOf(testWord);
}
Then test it with some code,
public static void main(String args[]) {
System.out.println(poitionOfWord("a"));
System.out.println(poitionOfWord("z"));
}
This prints,
1
-1
In general, when your function reaches a return statement, it will terminate and return the given value.
Suppose there is a string s=abcd
I want the 5th string consisting of a,b,c,d, which is adbc.
But I also get all the answers beyond it which I don't need.
So how can I stop this method after its 5th execution?
import java.util.Arrays;
import java.util.Scanner;
class Test{
long times;
int n=1;
public static void main(String[] args) {
Test tm=new Test();
Scanner in=new Scanner(System.in);
int t=Integer.parseInt(in.nextLine());
while(t!=0){
String s=in.nextLine();
char ch[]=s.toCharArray();
Arrays.sort(ch);
String sort=String.valueOf(ch);
String ans;
long n=Long.parseLong(in.nextLine());
tm.times=n;
tm.permu("",sort);
t--;
}
}
private void permu(String prefix,String str) {
int len=str.length();
if(len==0){
if(n==times){
System.out.println(prefix);
}
else{
n++;
}
}
else{
for(int i=0;i<len;i++){
permu(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, len));
}
}
}
}
Secondly is there any site where I can read about permutation, combination and probability for calculating and finding the permutation, combination and probability... For coding thing not for mathematical thing..i.e I know how to solve mathematically but I can't code it.. Unable to write logic for it.
You don't change n after running the check and printing a result in your recursion. That's why you print everything after adbc.
If you use this code when checking:
if (n == times) {
System.out.println(prefix);
n = -1;
} else {
if (n > -1)
n++;
}
then you only get n == times to be true once, and that's when the prefix is adbc.
Example test for the solution:
If you want to stop a method that has no return value (has void in its return type in the method signature), then calling return; will exit the method... But it isn't needed here.
So I'm trying to write recursive method indexOf which returns the starting index of the first occurrence of the second String inside the first String (or -1 if not found).For example, the call of indexOf (“Barack Obama”, “bam”) would return 8. Also I know that String class has method IndexOf, but I don't want to use it.
So far this is my code:
public class MyClass {
public static void main(String[] args) {
}
public static int indexOf(String s, String t) {
return abc(s, t, 0);
}
public static int abc(String a, String b, int c) {
if ((a.length() - c) < b.length()) {
return -1;
} else if (b.equals(a.substring(c, c + 3))) {
return c;
} else {
}
}
}
It depends how much of the library you want to use.
One option is:
int indexOf(String container, String text, int index) {
//Too short container
if (container.length() < text.length()) return -1;
//found
else if (container.startsWith(text)) return index;
//keep searching
else return indexOf(container.substring(1), text, index+1);
}
indexOf("banana", "nana", 0) == 2;
If you don't want to use .startsWith, then you need to implement your own version. A very good exercise would be to try and do this without ever using the .substring method, which is terrible (as it creates a copy of the string, O(n) space/time performance), and which is not needed for this task (use .charAt)
You can also split the official method indexOf from its recursive call that includes the index for more clarity).
You should think carefully about edge cases too :)
First of all this is not homework. Just me practicing.
I'm trying to recursively determine the number of times "hi" appears in the given string, but in every case it skips to the last else if statement and things the string is empty. Any ideas?
Basically,
if(string starts with "hi")
increment count by 1 and recurse with the string after the 2nd index to skip over the "hi" it just counted
else if(string does not start with "hi" and string is not empty)
recurse with the string after its 1st index to see if it starts with "hi" the next time around.
else if(string is empty)
Print("End of text reached")
return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
This is a good opportunity to practice debugging recursive functions calls -- actually quite difficult. Suggestions:
use strategically placed print-statements to ensure that the arguments are being changed correctly from one recursive invocation to the next
refactor the order of case-analysis in the if-statement to make it more clear. For example, 1) check if the string is empty (base case), 2) check if the string starts with "hi", 3) catch-all -- not empty and doesn't start with "hi"
As #Steve mentioned, you have to use the return value that recur returns.
See below for a modified version of your code, I also simplified your if/else statements:
public int recur(String str, int counter) {
if (str.startsWith("hi")) {
return recur(str.substring(2), counter+1);
} else if (!str.isEmpty()) {
return recur(str.substring(1), counter);
} else {
System.out.println("End of text reached");
return counter;
}
}
public static void main(String args[]) {
String str = "xxhixhixx";
Practice p = new Practice();
System.out.println(p.recur(str, 0));
}
You aren't using the value returned from recur.
public int countHi(String str) {
if (str.length() <= 1) {
return 0;
}
int count = 0;
if (str.substring(0, 2).equals("hi")) {
count = 1;
}
return count + countHi(str.substring(1)); //substring off
}
All this does is recursively count the number of the String "hi" inside a larger String. The rest of the implementations should be a piece of cake, happy Coding!
Your program printing 'End of text' is correct as finally as per the logic it will reach there, reason for count always coming as 0 is that in every iteration they change there own copy and finally when the termination condition is reached(String is empty) the result is popped out of the stack, hence final outcome that you receive is the pop of the first iteration where count was 0, so you have to return the value returned by recur at every step instead of returning count.
public static int recursive(String givenStr) {
int count =0 ;
Pattern pattern = Pattern.compile("hi");
Matcher match = pattern.matcher(givenStr);
while(match.find()){
System.out.println(match);
count++;
}
return count;
}
This Will return number of times "hi" has appeared into the String