PalindromeChecker comparTo - java

I am trying to make a Palindrome (the inverse of word is the word self e.g. tacocat) checker in java.
I use this code:
private static void PalindroomChecker(String sWord){
char[] arrcWord=sWord.toCharArray();
char[] arrcDrow=new char[arrcWord.length];
for(int i=0;i<arrcWord.length;i++)
for(int j=arrcDrow.length-1;j>=0;j--)
arrcDrow[j]=arrcWord[i];
String sDrow=new String(arrcDrow);
if(sWord.compareTo(sDrow)==0)
System.out.println(sWord);
else
System.out.println("false");
}
for some reason I keep printing false. So for some reason there are no palindrome's not even tacocat.

you only need the index. This should work.
private static void PalindroomChecker(String sWord) {
char[] arrcWord = sWord.toCharArray();
char[] arrcDrow = new char[arrcWord.length];
int i = 0;
for (int j = arrcDrow.length - 1; j >= 0; j--)
arrcDrow[j] = arrcWord[i++];
String sDrow = new String(arrcDrow);
if (sWord.compareTo(sDrow) == 0)
System.out.println(sWord);
else
System.out.println("false");
}

you might have got why your code doesn't work from other answers... here is a no loop approach it's much simpler::
public static void main(String[] args) {
String yourString = "tacocat";
StringBuilder a = new StringBuilder(yourString);
System.out.println(a.reverse().toString().equals(yourString) ? true : false);
}

Related

Java program to reverse a string not working?

I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?
There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.
Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}

Check if pattern exists in a String

I would like to check if a pattern exists in a String using iteration.
Here is what I have currently but I keep getting false as a result of it.
public static void main(String args[]) {
String pattern = "abc";
String letters = "abcdef";
char[] patternArray = pattern.toCharArray();
char[] lettersArray = letters.toCharArray();
for(int i = patternArray.length - 1; i<= 2; i++){
for(int j = lettersArray.length - 1; j <= 5;j++){
if(patternArray[i] == lettersArray[j]){
System.out.println("true");
} else{
System.out.println("false");
}
}
}
}
Basically I would like to check if abc exists in the String abcdef
Note: I don't want to use regex because is too easy. I am trying to find a solution without it because I am curious how to do it with iteration.
Here’s a naive string matching program that will find all matches of the pattern.
Not recommended for anything practical, because of the O(mn) time complexity (m and n are the lengths of the search string and pattern respectively).
class Potato
{
public static void main(String args[])
{
char[] search = "flow flow flow over me".toCharArray();
char[] pattern = "flow".toCharArray();
for(int i = 0; i <= search.length - pattern.length; i++)
// `-` don't go till the end of the search str. and overflow
{
boolean flag = true;
for(int j=0; j < pattern.length; j++)
{
if(search[i + j] != pattern[j])
{
flag = false;
break;
}
}
if (flag)
System.out.println("Match found at " + i);
}
}
}
Problem is you have two loops for each array. Here, you need single loop to traverse in both array using same index.
If you want to get all matches, i use a list to save matches addresses in the string.
String pattern = "abc";
String letters = "defabcdefabc";
int i = 0;
List<Integer> matches = new ArrayList();
while (i <= letters.length() - pattern.length()) {
if (letters.substring(i, i + pattern.length()).equals(pattern))
matches.add(i);
i += 1;
}
You can iterate matches if you want to loop all matches with this solution.
Edit:language changed
public static Boolean patternFinder(String str, String pattern){
for (int i = 0; i <= str.length()-pattern.length();i++){
Boolean found = true;
for (int f = 0; f < pattern.length();f++){
if (pattern.charAt(f) != str.charAt(i+f)){
found = false;
break;
}
}
if (found){
return true;
}
}
return false;
}
It's a very simple algorithm
basically, you loop through the string from the beginning and check if all the letters in the pattern are equal to the ones at that specific index.
Why not this:
public static void main(String args[]) {
String pattern = "abc";
String letters = "abcdef";
char[] patternArray = pattern.toCharArray();
char[] lettersArray = letters.toCharArray();
boolean matched = false;
for(int i = 0; i< lettersArray.length-patternArray.length && !matched; i++){
for(int j = 0; j < patternArray.length;j++){
if(patternArray[j] == lettersArray[i+j]&&j+1==patternArray.length){
matched = true;
System.out.println("true");
}
else if(i+1 == lettersArray.length-patternArray.length && j+1 == patternArray.length){
System.out.println("false");
}
}
}

Remove duplicates in a string in place in JAVA. No additional data structures are allowed

I recently came across this question and I implemented the same as follows:
public class DuplicateRemover
{
public static void removeDuplicates(char[] str)
{
int len = str.length;
boolean[] hit = new boolean[256];
for(int i = 0; i < hit.length; i++)
hit[i] = false;
int noDupindex = 0;
for(int i = 0; i < len; i++)
{
if( !hit[str[i]] )
{
str[noDupindex++] = str[i];
hit[str[i]] = true;
}
}
str[noDupindex] = '\0';
}
public static void main(String[] args)
{
char[] x = "hhhhhhefffff".toCharArray();
removeDuplicates(x);
System.out.println(x);
}
}
But the output shown is "hef hhefffff". The literal '\0' is added to the char array at the end and still while printing it prints the elements after the literal '\0'. Why is it so? Please let me know if I miss something.
x is not a String object. It's an array of char. When you print an array of char, every element is printed. It does not stop on a null char.
Java strings are not terminated by '\0'. You are thinking of C and C++.
The size of an array cannot be changed after its creation, so removeDuplicates can't resize the array. I would recommend that removeDuplicates either returns a new array, or just returns a new String.
Besides above great answers, you could also use StringBuilder in java to align with your original intent as this:
public class DuplicateRemover
{
public static void removeDuplicates(StringBuilder str)
{
int len = str.length();
boolean[] hit = new boolean[256];
for(int i = 0; i < hit.length; i++)
hit[i] = false;
int noDupindex = 0;
for(int i = 0; i < len; i++)
{
if( !hit[str.charAt(i)] )
{
str.setCharAt(noDupindex++, str.charAt(i));
hit[str.charAt(i)] = true;
}
}
str.delete(noDupindex, str.length());
}
public static void main(String[] args)
{
StringBuilder x = new StringBuilder("hhhhhhefffff");
removeDuplicates(x);
System.out.println(x);
}
}
I'd recommend using the null character to signify when to print. As immibis pointed out, Java strings are not terminated by the null character.
However you can create a method to adhere to this.
public static void printString(final char[] str){
int length = str.length;
if(length == 0){
return;
}
int counter = 0;
while(counter < length && str[counter] != 0){
System.out.print(str[counter++]);
}
}
You can then just do:
public static void main(String[] args)
{
char[] x = "hhhhhhefffff".toCharArray();
removeDuplicates(x);
printString(x);
}
Try this example:
public static String trunc(String str) {
char[] buff = {}, tmp = null;
boolean found;
for(char c : str.toLowerCase().toCharArray()) {
found = false;
for(char i : buff) {//search in buff for duplicate
if(i == c) {//found duplicate
found = true;
break;
}
}
if(!found) {//not duplicate
tmp = buff;
buff = new char[buff.length + 1];//new array with +1 size for new character
System.arraycopy(tmp, 0, buff, 0, tmp.length);//copy tmp into buff
buff[tmp.length] = c;//store the new character
}
}
return new String(buff);
}

Alternate display of 2 strings in Java

I have a java program where the following is what I wanted to achieve:
first input: ABC
second input: xyz
output: AxByCz
and my Java program is as follows:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
however I encounter the following runtime error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
What mistake is in my Java program?
If both arrays have same length for loop should continue while i < anyArray.length.
Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.
So your displayStringAlternately method can look like
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).
As you commented, If both arrays length is same, you can simply do
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
Then
for(int i = 0; i < firstC.length; i++) {
System.out.print(firstC[i]);
System.out.print(secondC[i]);
}
Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.
Try the below working code with high performance
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < firstC.length; i++) {
builder.append(firstC[i]);
builder.append(secondC[i]);
}
System.out.println(builder.toString());
}
public class concad {
public void main(String[] args) {
String s1 = "RAMESH";
String s2 = "SURESH";
int i;
int j;
for (i = 0; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
for (j = i; j <= i; j++) {
if (j == i) {
System.out.print(s2.charAt(j));
}
}
}
}
}
I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.
public class AlternatePosition {
public static void main(String[] arguments) {
String abc = "abcd";
String def = "efgh";
displayStringAlternately(abc, def);
}
public static void displayStringAlternately(String firstString, String secondString) {
for (int i = 0; i < firstString.length(); i++) {
for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
if (counter % 2 == 0) {
System.out.print(secondString.charAt(i));
break;
} else {
System.out.print(firstString.charAt(i));
}
}
}
}
}

Can anybody help me to correct the following code?

Please help me to identify my mistakes in this code. I am new to Java. Excuse me if I have done any mistake. This is one of codingbat java questions. I am getting Timed Out error message for some inputs like "xxxyakyyyakzzz". For some inputs like "yakpak" and "pakyak" this code is working fine.
Question:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
public String stringYak(String str) {
String result = "";
int yakIndex = str.indexOf("yak");
if (yakIndex == -1)
return str; //there is no yak
//there is at least one yak
//if there are yaks store their indexes in the arraylist
ArrayList<Integer> yakArray = new ArrayList<Integer>();
int length = str.length();
yakIndex = 0;
while (yakIndex < length - 3) {
yakIndex = str.indexOf("yak", yakIndex);
yakArray.add(yakIndex);
yakIndex += 3;
}//all the yak indexes are stored in the arraylist
//iterate through the arraylist. skip the yaks and get non-yak substrings
for(int i = 0; i < length; i++) {
if (yakArray.contains(i))
i = i + 2;
else
result = result + str.charAt(i);
}
return result;
}
Shouldn't you be looking for any three character sequence starting with a 'y' and ending with a 'k'? Like so?
public static String stringYak(String str) {
char[] chars = (str != null) ? str.toCharArray()
: new char[] {};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
// then it's unlucky...
i += 2;
continue; //skip the statement sb.append
} //do not append any pattern like y1k or yak etc
sb.append(chars[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
// The result will be 1234.
}
It looks like your programming assignment. You need to use regular expressions.
Look at http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex for more information.
Remember, that you can not use contains. Your code maybe something like
result = str.removeall("y\wk")
you can try this
public static String stringYak(String str) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='y'){
str=str.replace("yak", "");
}
}
return str;
}

Categories