Java Anagram - Simple Challenge [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello Stack Overflow Community. I developed a simple Java program to detect whether or not a word entered by the user is an Anagram. I do not receive the expected output based on the boolean value. Any ideas or suggestions are appreciated.
Note: This code does not include any methods or class functions that would make this a rather simple solution. Please work with the code below. Thank you!
import javax.swing.*;
public class Anagram
{
public static String word = " ";
public static boolean match = false;
public static void main(String[] args)
{
//Prompt the User for a Word
word = JOptionPane.showInputDialog("Please Enter A Word");
//Break the Word into an Array
String[] anagram = new String[word.length()];
for(int i = 0; i < word.length(); i++)
{
anagram[i] = Character.toString(word.charAt(i));
JOptionPane.showMessageDialog(null, anagram[i]);
}
//Create a duplicate Array
String[] anagram2 = new String[word.length()];
for(int i = word.length() - 1; i >= 0; i--)
{
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
//Do a search on each letter
for (int i = 0; i < anagram.length && i < anagram2.length; i++)
{
if(anagram.length == anagram2.length)
{
if(anagram[i].toLowerCase() == anagram2[i].toLowerCase())
{
match = true;
}
else
{
match = false;
}
}
else
{
JOptionPane.showMessageDialog(null, "There is a mismatch");
match = false;
}
}
//Prompt the user with the result
if(match == true)
{
JOptionPane.showMessageDialog(null, "Your Word is a Anagram!");
}
else if(match == false)
{
JOptionPane.showMessageDialog(null, "Your Word is NOT a Anagram!");
}
}
}

Assuming you mean palindrome:
Your code doesn't actually reverse the String.
for(int i = word.length() - 1; i >= 0; i--) {
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
This copies anagram into anagram2 without reversing it - it does go through it from back to front, but the result will be the same.
You need to do something like
for (int i = 0; i < word.length(); i++) {
anagram2[word.length() - i - 1] = anagram[i];
}
However, there really is no need to create the anagram and anagram2 arrays in the first place, you can just iterate through the String's data itself using charAt.
boolean match = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
match = false;
break;
}
}
Side note, you shouldn't declare word and match as static variables, keeping them local in main() will do.

Related

How to optimize the longest subsequence generation code in java?

import java.util.Scanner;
public class POD9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String tito_has = sc.nextLine();
String tito_wants = sc.nextLine();
String remaining = "";
int strips = 0;
while(true){
String longest_common = getLongestCommonSubstring(tito_has,tito_wants);
strips++;
tito_has = tito_has.replaceAll(longest_common,"*");
remaining = remaining + longest_common;
if(remaining.length() == tito_wants.length()){
break;
}
}
System.out.println(strips-1);
}
public static String getLongestCommonSubstring(String str1, String str2){
int m = str1.length();
int n = str2.length();
int max = 0;
int[][] dp = new int[m][n];
int endIndex=-1;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(str1.charAt(i) == str2.charAt(j) && str1.charAt(i) != Character.valueOf('*'))
{
if(i==0 || j==0){
dp[i][j]=1;
}else{
dp[i][j] = dp[i-1][j-1]+1;
}
if(max < dp[i][j])
{
max = dp[i][j];
endIndex=i;
}
}
}
}
return str1.substring(endIndex-max+1,endIndex+1);
}
}
This is my code used to retrieve the minimum number of paper cuts that are needed to form string 2 from string 1. This is the solution to the problem: Paper Cut Problem
I approached the problem by finding the longest substring between what Tito wants and what he has.
Thereafter, I replace the found sequences with '' as the input will only have letters. Also, in the cases, say, it has: "abbap" and tito wants:"bbaap", then this gives 3 cuts a|bb|a|p and not
2 (found bb->remove it (cut 1)->got (aap) -> found aa(cut2)-> remove it-> found b). So using "" helps in not making wrong substrings match.
I am pretty sure that my approach will solve most of the test cases. But I am getting the TIMELIMIT error here.
Please help me find an optimum way to achieve this?

Java Poem Palindrome Checker: Iterate through array matching elements in order

Currently trying to program a poem Palindrome checker. This is not for palindromes specifically, but that the array has words in the same order both ways. For example the following is a poem palindrome
Life-
imitates nature,
always moving, traveling continuously.
Continuously traveling, moving always,
nature imitates
life
My issue is iterating through the array to match the first and last elements, as currently it compares things in the wrong order.
My code is as follows:
import java.util.Scanner;
import java.io.*;
public class WordPalindromeTest {
public static void main(String[] args) {
System.out.println("This program determines if an entered sentence/word poem is a palindrome.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string to determine if it is a palindrome: ");
while(input.hasNextLine()) {
String palin = input.nextLine();
if(palin.equals("quit")) {
break;
}
else {
boolean isPalin = isWordPalindrome(palin);
if(isPalin == true) {
System.out.println(palin + " is a palindrome!");
}
else
System.out.println(palin + " is NOT a palindrome!");
}
}
System.out.println("Goodbye!");
input.close();
}
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
}
With the specific point in question being
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
I am confused on how to properly set up the loop to compare the right elements. It should compare the first element to the last, the second to the second to last, etc. until the loop is finished. I realize I have it compare the first to the entire array before moving on.
This seems like a homework assignment so I won't give you a working solution. But this of it like this:
-You don't need two loops. You only need to compare the first to the last, the second to the second to last, etc. (Hint: if you subtract i-1 from the length of the Array you'll get the corresponding element to i that you need to compare to). Also you only need to iterate over half of the length of the Array
-If ever isWordPal becomes false, you need to return false. Otherwise it might get overwritten and at the end it will return true.

What am I doing Wrong here [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I made a program to search for a certain string in another string and print Word found if the condition is true or print word not found if condition is false
The logic is as follows
enter word
length of word
for searching for letter [1]
if true
then for till length of word match with string to be searched
else continue loop
But I always get word not found no matter what the input, please help me over here!!!
The code is as follows :-
import java.util.Scanner;
class Search_i_String
{
public static void main(String args[])
{
int flag=0;
Scanner Prakhar=new Scanner(System.in);
System.out.println("Enter a String");
String ori=Prakhar.nextLine();
System.out.println("Enter the String to be Searched");
String x=Prakhar.nextLine();
char a[]=new char[ori.length()];
char b[]=new char[x.length()];
for(int i=0;i<ori.length();i++)
{
a[i]=ori.charAt(i);
}
for(int i=0;i<x.length();i++)
{
b[i]=x.charAt(i);
}
for(int i=0;i<a.length;i++)
{
if (a[i]==b[0])
{
for(int j=0;j<b.length;j++)
{
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
}
}
}
}
if (flag==0)
{
System.out.println("Word Found !!!");
}
else
System.out.println("Word not Found");
}
}
P.S. : I know I can use the contains() function but I can as my professor suggests against it and could someone please correct the program I have written, because I could have scavenged off a program from the internet too if I had to, I just wanted to use my own logic
Thank You(again)
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
j++; //add this and try once
}
If you are comparing strings in Java, you have to use equals();
So, stringA.equals(stringB);
Cheers!
Let me get this straight. You're looking for b array inside of a array? "Enter the string to be searched" means that you are searching the other way around, but I'll go with the logic your code seems to follow... Here's a naive way to do it:
if (a[i]==b[0])
{
flag = 0;
for(int j=0;j<b.length;j++)
{
if(b[j] != a[i+j]) // will array index out of bounds when its not foud
{
flag++; // you should probably break out of a named loop here
}
}
if(flag == 0){/*win*/}
}
You're modifying your first search loop with variable i when you don't have to. You can just add i to j. Also, you don't need the while loop inside if i'm understanding your problem. Like others have said, functions exist to do this already. This algorithm isn't even as efficient as it could be.
I know of an algorithm where you check starting in the last character in b instead of the first character in b to begin with. Then you can use that information to move your search along faster. Without resorting to full pseudo code, anyone know what that's called?
The simple way(but not the fastest way) is use double loop to check the chars in strings one by one, pls ref to my code and comments:
public class SearchString {
public static void main(String[] args) {
String a = "1234567890";
String b = "456";
// Use toCharArray() instead of loop to get chars.
search(a.toCharArray(), b.toCharArray());
}
public static void search(char[] a, char[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
System.out.println("Error: Empty Input!");
return;
}
int lenA = a.length, lenB = b.length;
if (lenA < lenB) {
System.out
.println("Error: search key word is larger than source string!");
return;
}
// Begin to use double loop to search key word in source string
for (int i = 0; i < lenA; i++) {
if (lenA - i < lenB) { // If the remaining source string is shorter than key word.
// Means the key word is impossible to be found.
System.out.println("Not found!");
return;
}
// Check the char one by one.
for (int j = 0; j < lenB; j++) {
if (a[i + j] == b[j]) {
if (j == lenB - 1) { // If this char is the last one of key word, means it's found!
System.out.println("Found!");
return;
}
} else {
// If any char mismatch, then right shift 1 char in the source string and restart the search
break;
}
}
}
}
}
You can just use String.contains();
If you really want to implement a method, try this one:
public static void main(String[] args) {
// Initialize values searchedWord and original by user
String original = [get original word from user] ;
String searchedWord = [get searched for word from user];
boolean containsWord = false;
int comparePosition = 0;
for(int i = 0; i < original.length() - searchedWord.length(); i++) {
if(original.charAt(i) == searchedWord.charAt(comparePosition)) {
comparePosition += 1;
} else {
comparePosition = 0;
}
if(comparePosition == searchedWord.length()) {
containsWord = true;
break;
}
}
return containsWord? "Word found!!" : "Word not found.";
}

Breaking line - Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I break a line automatically into many lines without cutting off words? And the length for each new line will be around 4 words? I have many sentences thus I cannot use \n
e.g:
If I were you I would go to the cinema with her
becomes:
If I were you
I would go to
the cinema with her
Hope see your help soon. Thanks!
I would imagine, based on what you put although I'm not sure you're considering all possible cases, a way to get the specific answer you're looking for while taking a few things for granted and not directly relying on "\n" would be...
String s = "If I were you I would go to the cinema with her";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if(i % 4 == 0) {
System.out.println();
}
System.out.print(strings[i] + " ");
}
Alternatively you might consider something like this, which would handle a max width of your text field as opposed to a set number of words since some words may be very long and cause a situation which you're trying to avoid...
int MAX = 20;
int length = 0;
String s = "If I were you I would go to the cinema with her.";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if((length + strings[i].length()) > MAX ) {
System.out.println();
length = 0;
}
System.out.print(strings[i] + " ");
length += strings[i].length() + 1;
}
Edit:
I did as you requested. This is what I get from the MAX option...
If I were you I
would go to the
cinema with her and
abc xyz
And this is what I get for the regular...
If I were you
I would go to
the cinema with her
and abc xyz
Not sure what's happening there, but I will say I jumped the shark on my answer. You've tagged Android and you and I both know System.out.println() is a no-no in that environment, at least if you expect to see any results. Sorry about that.
you need to count the number of spaces in a for loop here is a code to demonstrate it. please change the variables according to your application
String tv2 = tv.getText().toString(); // take a string textVIew, you can make it editView
StringBuilder sb = new StringBuilder(tv2); // add the string to stringBuilder
int howManySpaces = 0; // this for counting the spaces.
for (int i = 0; i < tv2.length(); i++)
{
if (tv2.charAt(i) == ' ') //if space found add one to howManySpaces
{
howManySpaces += 1;
Log.d("HMS", String.valueOf(howManySpaces));
}
if (howManySpaces == 4) // if howManySpaces == 4 break it to new line
{
sb.replace(i, i+1, "\n");
howManySpaces = 0;
}
}
tvNew.setText(sb.toString()); // add to the new textView the result after breaking.
I just tried it right now, with same sentences it gave me the desired result.
feel free to ask me if you didnt understand any part.
I have tried the following code, it worked fine for me, please try this and kindly let me if you have any trouble on this
// Calling the SentenceBreaker method which helps the String to split.
sentenceBreaker("If I were you I would go to the cinema with her");
// Method which spilts the Sentence
private void sentenceBreaker(int noOfWords,String inputSentence){
boolean previousCharWhiteSpace = true; // just a flag
boolean initialFlag =false;
int wordCount = 0;
int i,count =0;
for (i = 0; i < inputSentence.length(); i++) {
if (inputSentence.charAt(i) == ' ' && !previousCharWhiteSpace) {
wordCount++;
previousCharWhiteSpace = true;
if (wordCount == noOfWords) {
if(count == 0){
inputSentence = inputSentence.substring(0,wordCount)
+ "\n"
+ inputSentence.substring(wordCount,
inputSentence.length());
wordCount = 0;
count=i;
}
else{
inputSentence = inputSentence.substring(count, i)
+ "\n"
+ inputSentence.substring(i,
inputSentence.length());
wordCount = 0;
count=i;
}
}
} else if (!(inputSentence.charAt(i) == ' ')) {
previousCharWhiteSpace = false;
}
}
/*
* the for loop increments the word count if a space is encountered
* between words,for multiple spaces between words it wont update the
* counter-hence the use of the boolean flag.
*/
if (!(inputSentence.charAt(i - 1) == ' ')) {
wordCount++;
}
// just to make sure that we count the last word in the sentence as well
System.out.println("No of words-" + wordCount);
System.out.println("Sentence" + inputSentence);
}
/* Output */
Sentence If I were you
I would go to
the cinema with her**
As Per Your Requirement..Following logic will be works fine..Please Use it
String stT="If I were you I would go to the cinema with her";
String[] sT=stT.split(" ");
StringBuffer sb=new StringBuffer();
for(int i=0;i<sT.length;i++)
{
if(i%4==3)
sb.append(sT[i]+"\n");
else
sb.append(sT[i]+" ");
}
System.out.print(sb.toString());

Get the longest substring from a string which is passed in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I want to pass in a string into a method e.g. "abbcccdef" and want it to return the longest substring. in this case it would be "ccc". Someone please help me with code that would help me solve this issue. I would like something basic that would allow a beginner to understand easily. This is what i have so far but it doesnt seem to work:
Many Thanks
public String getLongestSubstring(String s) {
int [] length = new int [s.length()];
String longestString = "";
if (s.length() > 0) {
char c = s.charAt(0);
for (int i=0;i<s.length();i++) {
for (int j=0;j<s.length();j++) {
if (c==s.charAt(j)) {
length [i]++;
} else {
c = s.charAt(j);
i++;
}
}
}
return longestString;
}
else
return null;
}
Follow the bellow mentioned algorithm sub-string sequence
I haven't tested this and I found and fixed one error already, but I think I've covered all the bases now. One limitation you didn't elaborate on in your question was the case in which there are two substrings of equal, longest length. i.e. abbbcccdef, I just return the first.
public String getLongestSubstring(String s)
{
if (s.length() == 0) return null;
//We need some data to start with.
char currentChar = s.charAt(0);
String longestString = "" + currentChar;
String runningString = "" + currentChar;
int currentLongestLength = 1;
for (int i = 1; i < s.length(); i++)
{
//Check the current char, is it the same?
if (s.charAt(i) == currentChar)
{
runningString = runningString + currentChar;
//Have we beaten our previous record.
if (runningString.length() > longestString.length())
{
//Increase the record.
currentLongestLength++;
longestString = runningString;
}
}
else
{
runningString = "" + s.charAt(i);
}
}
return longestString;
}
Here is how I implemented to find a longest SubString from a String.
public class LongestString {
public static void main (String[] args) throws java.lang.Exception {
System.out.println("Longest Substring is " + getLongestSubstring("abbcccdf"));
}
public static String getLongestSubstring(String s) {
int length = 1;
String longestString = "";
for (int i = 0; i < s.length(); i++) {
StringBuilder str = new StringBuilder();
str.append(s.charAt(i));
for (int j = i + 1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
str.append(s.charAt(j));
} else {
break;
}
}
if (length < str.length()) {
length = str.length();
longestString = str.toString();
}
}
return longestString;
}
}
Test it: http://ideone.com/JM904Y
public String getLongestSubString(String source) {
StringBuilder longestStringBuilder = new StringBuilder(source.length());
String longestString = "";
for(int i=0; i<source.length(); i++) {
if(longestStringBuilder.toString().contains(String.valueOf(source.charAt(i)))) {
if(longestString.length() < longestStringBuilder.toString().length()) {
longestString = longestStringBuilder.toString();
}
longestStringBuilder.setLength(0);
}
longestStringBuilder.append(source.charAt(i));
}
if(longestString.length() < longestStringBuilder.toString().length()) {
longestString = longestStringBuilder.toString();
}
return longestString;
}

Categories

Resources