I'm trying to create a method shuffle (String stri, String str2, String str3) that returns a boolean and take two Strings and "shuffles" them to make a third String, but I'm trying to do it recursively, which is kind of tough for me to think about. I want to return true if str1 and str2can be shuffled and return false if they can't be shuffled.
For example, if str1 = "tv" and str2 = "aol", the method might return taovl.
I also plan to test the method out as well as create another helper method to make it more efficient, but that's easy.
import java.util.Scanner;
public class lab3{
public static void main(String[] args) {
String str;
System.out.print("Enter String: ");
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
String res = revRec3(str);
System.out.println(res);
}
public static String revRec3(String str)
{
if (str.length() <= 1)
return str;
else{
String first = str.substring(0, str.length() / 3);
String second = str.substring(str.length() / 3, ((2 * str.length()) / 3));
String third = str.substring((2 * str.length()) / 3, str.length());
return revRec3(third)+revRec3(second)+revRec3(first);
}
}
}
try doing something like this. This Program splits a String into 3 pieces and then reverses them using recursion.
I solved this by simply creating three integer variables to go through the indices of all three strings and checking to see if a a letter at any index matches the same order of s3
Related
and thank you for helping me.
So my question is i need a code that asks you for a String like "1234 567" (input), then returns the string numbers like "1 2 3 4 5 6 7" (output) once more
my current code is:
public class StringComEspaços {
public static String formatNumberWithSpaces(String inputString) {
String outputString = "222";
return outputString;
}
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
}
thanks for the help, and sorry for bad english :).
There are many possible ways to solve your problem.
You can do it in an OO way with StringBuilder:
public static String formatNumberWithSpaces(String inputString) {
StringBuilder output = new StringBuilder();
for (char c : inputString.toCharArray()) // Iterate over every char
if (c != ' ') // Get rid of spaces
output.append(c).append(' '); // Append the char and a space
return output.toString();
}
Which you can also do with a String instead of the StringBuilder by simply using the + operator instead of the .append() method.
Or you can do it a more "modern" way by using Java 8 features - which in my opinion is fun doing, but not the best way - e.g. like this:
public static String formatNumberWithSpaces(String inputString) {
return Arrays.stream(input.split("")) // Convert to stream of every char
.map(String::trim) // Convert spaces to empty strings
.filter(s -> !s.isEmpty()) // Remove empty strings
.reduce((l, r) -> l + " " + r) // build the new string with spaces between every character
.get(); // Get the actual string from the optional
}
Just try something that works for you.
Try out this function:
public static String formatNumberWithSpaces(String inputString){
String outputString = ""; //Declare an empty String
for (int i = 0;i < inputString.length(); i++){ //Iterate through the String passed as function argument
if (inputString.charAt(i) != ' '){ //Use the charAt function which returns the char representation of specified string index(i variable)
outputString+=inputString.charAt(i); //Same as 'outputString = outputString + inputString.charAt(i);'. So now we collect the char and append it to empty string
outputString+=' '; //We need to separate the next char using ' '
} //We do above instruction in loop till the end of string is reached
}
return outputString.substring(0, outputString.length()-1);
}
Just call it by:
System.out.println(formatNumberWithSpaces("123 222 2222"));
EDIT:
Or if you want to ask user for input, try:
Scanner in = new Scanner(System.in);
System.out.println("Give me your string to parse");
String input = in.nextLine(); //it moves the scanner position to the next line and returns the value as a string.
System.out.println(formatNumberWithSpaces(input)); // Here you print the returned value of formatNumberWithSpaces function
Don't forget to import, so you will be able to read user input :
import java.util.Scanner;
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
EDIT2:
I changed:
return outputString;
..to: return outputString.substring(0, outputString.length()-1);
Just because outputString+=' '; was also appending empty space at the end of string, which is useless. Didn't add an if inside for loop which wouldn't add space when last char is parsed, just because of its low performance inside for loop.
use this code.
public class StringComEspaços {
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
private static String formatNumberWithSpaces(String string) {
String lineWithoutSpaces = string.replaceAll("\\s+", "");
String[] s = lineWithoutSpaces.split("");
String os = "";
for (int i = 0; i < s.length; i++) {
os = os + s[i] + " ";
}
return os;
}
}
I want to create a method called filterOut that accepts two string as arguments and returns the first string with all instances of the second string removed. Ex: filterOut("hello my friend, how are you?" , "h"); returns "ello my friend, ow are you?" and filterOut("abchelloabcfriendabc" , "abc"); returns "hellofriend"
public static String filterOut(String phrase, String second){
int counter = 0;
int length = phrase.length();
String filtered = "";
while(counter < length){
String letter = phrase.substring(counter, counter + 1);
if(!letter.equals(second)){
filtered = filtered + letter;
}
counter++;
}
return filtered;
public static void main(String args[]){
String next = filterOut("hello my friend, how are you?" , "h");
System.out.println(next);
}
This code only works for the first example when I use it in the main method. How can I get it to work for the second example as well?
You can simply do:
str1.replace(str2, "");
Or in your example,
second.replace(phrase, "");
Also: there is no need to write a method for this, when there already is one :-)
You can use replace
public static String filterOut(String phrase) {
return phrase.replace(phrase, "");
}
Edit:
You can also use split method
public static String filterOut(String phrase, String second) {
String filtered = "";
for (String each : phrase.split(second)) {
filtered = filtered + each;
}
return filtered;
}
Your method wont work because you are comparing character by character in the below line. So that's why it will work for filterOut("hello my friend, how are you?" , "h"); and not work for input filterOut("abchelloabcfriendabc" , "abc");
String letter = phrase.substring(counter, counter + 1);
if(!letter.equals(second)){
filtered = filtered + letter;
}
I have two strings with me:
s1="MICROSOFT"
s2="APPLESOFT"
I need to compare the strings and remove the duplicate part (always towards the end) from the second string. So I should get "MICROSOFT" and "APPLE" as output.
I have compared both the strings character by character.
String s1 = "MICROSOFT";
String s2 = "APPLESOFT";
for(int j=0; j<s1.length(); j++)
{
char c1 = s1.charAt(j);
char c2 = s2.charAt(j);
if(c1==c2)
System.out.println("Match found!!!");
else
System.out.println("No match found!");
}
It should check the strings and if the two strings have same characters until the end of string, then I need to remove that redundant part, SOFT in this case, from the second string. But I can't think of how to proceed from here.
There can be more duplicates...but we have to remove only those which are continuously identical. if i have APPWWSOFT and APPLESOFT, i should get APPLE again in the second string since we got LE different than WW in between
Can you guys please help me out here?
Search and read about Longest Common Subsequence, you can find efficient algorithms to find out the LCS of two input strings. After finding the LCS of the input strings, it is easy to manipulate the inputs. For example, in your case an LCS algorithm will find "SOFT" as the LCS of these two strings, then you might check whether the LCS is in the final part of the 2nd input and then remove it easily. I hope this idea helps.
An example LCS code in Java is here, try it: http://introcs.cs.princeton.edu/java/96optimization/LCS.java.html
Example scenario (pseudocode):
input1: "MISROSOFT";
input2: "APPLESOFT";
execute LCS(input1, input2);
store the result in lcs, now lcs = "SOFT";
iterate over the characters of input2,
if a character exists in lcs then remove it from input2.
As far as I understand, you want to remove any identical characters from the two strings. By identical I mean: same position and same character(code). I think the following linear complexity solution is the simplest:
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(); //if you want to remove the identical char
//only from one string you don't need the 2nd sb
char c;
for(int i = 0; i<Math.min(s1.length,s2.length);i++){
if((c = s1.charAt(i)) != s2.charAt(i)){
sb1.append(c);
}
}
return sb1.toString();
Try this algo- Create characters sequences of your first string and find it in second string.
performance -
Average case = (s1.length()-1)sq
public class SeqFind {
public static String searchReplace(String s1,String s2) {
String s3;
boolean brk=false;
for(int j=s1.length();j>0&&!brk;j--){
for (int i = j-4; i > 0; i--) {
String string = s1.substring( i,j);
if(s2.contains(string)){
System.out.println(s2+" - "+string+" "+s2.replace( string,""));
brk=true;
break;
}
}
}
return s3;
}
public static void main(String[] args) {
String s1 = "MICROSOFT";
String s2 = "APPLESOFT";
String s3 = searchReplace(s1,s2);
}
}
Out put -
APPLESOFT - SOFT - APPLE
public class Match {
public static void main(String[] args)
{
String s1="MICROSOFT";
String s2="APPLESOFT";
String[] s=new String[10];
String s3;
int j=0,k=0;
for(int i=s2.length();i>0;i--)
{
s[j]=s2.substring(k,s2.length());
if(s1.contains(s[j]))
{
s3=s2.substring(0,j);
System.out.println(s1+""+s3);
System.exit(0);
}
else
{
System.out.println("");
}
j++;
k++;
}
}
}
I have edited the code you can give it an another try.
try this, not tested thou
String s1 = "MICROSOFT";
String s2 = "APPLESOFT";
String s3="";
for(int j=0; j<s1.length(); j++)
{
if(s1.charAt(j)==s2.charAt(j)){
s3+=s1.charAt(j);
}
}
System.out.println(s1.replace(s3, " ") + " \n"+ s2.replace(s3, " "));
You should rather use StringBuffer if you want your String to be modified..
And in this case, you can have one extra StringBuffer, in which you can keep on appending non-matching character: -
StringBuffer s1 = new StringBuffer("MICROSOFT");
StringBuffer s2 = new StringBuffer("APPLESOFT");
StringBuffer s3 = new StringBuffer();
for(int j=0; j<s1.length(); j++)
{
char c1 = s1.charAt(j);
char c2 = s2.charAt(j);
if(c1==c2) {
System.out.println("Match found!!!");
} else {
System.out.println("No match found!");
s3.append(c1);
}
}
s1 = s3;
System.out.println(s1); // Prints "MICRO"
I have solved my problem after racking some brains off. Please feel free to correct/improve/refine my code. The code not only works for "MICROSOFT" and "APPLESOFT" inputs, but also for inputs like "APPWWSOFT" and "APPLESOFT" (i needed to remove the continuous duplicates from the end - SOFT in both the above inputs). I'm in the learning stage and I'll appreciate any valuable inputs.
public class test
{
public static void main(String[] args)
{
String s1 = "MICROSOFT";
String s2 = "APPLESOFT";
int counter1=0;
int counter2=0;
String[] test = new String[100];
test[0]="";
for(int j=0; j<s1.length(); j++)
{
char c1 = s1.charAt(j);
char c2 = s2.charAt(j);
if(c1==c2)
{
if(counter1==counter2)
{
//System.out.println("Match found!!!");
test[0]=test[0]+c2;
counter2++;
//System.out.println("Counter 2: "+counter2);
}
else
test[0]="";
}
else
{
//System.out.print("No match found!");
//System.out.println("Counter 2: "+counter2);
counter2=counter1+1;
test[0]="";
}
counter1++;
//System.out.println("Counter 1: "+counter1);
}
System.out.println(test[0]);
System.out.println(s2.replaceAll(test[0]," "));
}
}
So I need to find the longest word recursively, I've written the code, but it's not working, and I have no idea what to fix.
public static String longestWord(String sentence)
{
int i = sentence.indexOf(" ");
if (i==-1){
return sentence;
}
else{
String first = sentence.substring(0,i);
String rest = sentence.substring(i+1);
if(first.length()>=rest.length()){
return longestWord(first);
}
else{
return longestWord(rest);
}
}
}
The line:
if(first.length() >= rest.length())
should read like:
String res = longestWord(rest);
if(first.length() >= res.length())
The reason it does not work is that you are ignoring the length of the longestWord(rest): instead of comparing the length of the initial word and the rest of the sentence, you should compare the length of the initial word to the length of the longest word found in the rest of the sentence.
String first = sentence.substring(0,i);
String rest = longestWord(sentence.substring(i+1));
return first.length()>=rest.length() ? first : rest;
Your basic approach is sane: you're breaking the input into two: the first word, and the rest of the string. But then the logic is bungled a little bit.
If the first word is longer than the entire rest of the string, you should just return first, not longestWord(first) (although, you do handle that case: longestWord will notice that the word cannot be split and just return it. It's pointless though).
Secondly, if that is not the case, you cannot assume that the first word is not the longest word. You must capture the return value of longestWord(rest), and then compare that word's length to the length of first. If that word is longer, then return it. Otherwise return first.
The essence of "divide and conquer" by recursion is that you solve some smaller versions of the problem, and then integrate those results. Don't forget this second part. This is not a binary search tree search where the data is organized such that you can just recurse to one half of the space or the other to find the answer. You don't know where the longest word might be.
This is another approach to solve the question:
public static String longestWord(String sentence) {
return longest(sentence.split("\\s+"), 0, 0);
}
private static String longest(String[] words, int idx, int longest) {
if (idx == words.length)
return words[longest];
return longest(words, idx+1,
words[idx].length() > words[longest].length() ? idx : longest);
}
First, in longestWord() the sentence gets split by its spaces, producing an array of words. From that point on, the method longest() recursively iterates over all the words passing the index of the longest one found so far in the longest parameter, until there are no more words. This is an efficient answer, as it doesn't create substrings at each step.
package com.kota.java;
import java.util.*;
class LongestWord{
String str = "Ram is intelligent boy";
String stringArray[] = str.split("\\s");
public String compare(String st1, String st2) {
if (st1.length() > st2.length()) {
return st1;
} else {
return st2;
}
}
LongestWord() {
String word = "";
for (int i = 0; i < stringArray.length; i++) {
if (i == 0) {
word = stringArray[0];
}
word = compare(word, stringArray[i]);
}
System.out.println("Longest word = " + word);
}
public static void main(String[] args) {
new LongestWord();
}
}
/**
* Out put : Longest word = intelligent
*
* */
I have a multipart string like this:
String Y = "part1 part2 part3 part4"; // This is only an example value
I want to write a function that compares the complete string Y with another strin, X. (Normally I will compare it with a list.) If the strings are not equal, then part1 part2 part3 should be compared with X. If they are not equal, X should be compared with part1 part2, and then finally with just part1.
I can use split(" ") to break the string up. I don't know the number of chunks in the string. How can I write this comparison method?
You can use an algorithm like this:
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = Y.useSplitToRemoveLastPart();
if(Y.equals("")) {
break;
}
}
}
That's only pseudocode, of course. It seemed like you had a general idea how to do each of these individual parts. If you need more guidance, just let me know.
EDIT:
Assuming your strings will always be space-delimited like they are in your example, you could do something like this:
String userSplitToRemoveLastPart(String Y) {
// Find the last space
int lastSpace = Y.lastIndexOf(" ");
// Return only the part of the string that comes before the last space
return Y.substring(0, lastSpace);
}
I haven't tested this, and it may not be the most efficient way to perform the split, but I think the algorithm is clear.
Something like this should get you started:
class SpecialComparator implements Comparator<String> {
public int compare(String o1, String o2) {
// Get parts to compare
String[] words1 = o1.split(" ");
String[] words2 = o2.split(" ");
// Reverse arrays to start with the last word first.
Collections.reverse(Arrays.asList(words1));
Collections.reverse(Arrays.asList(words2));
int n = Math.min(words1.length, words2.length);
for (int i = 0; i < n; i++) {
int result = words1[n].compareTo(words2[i]);
if (result != 0) // not equal, differing words found.
return result;
}
// Deal with the situation in which the strings are of different length.
// ...
// They're equal.
return 0;
}
}
I'm a little confused by your expected outcome. The goal seems to be to simply count partial matches, which this accomplishes:
public boolean foo(final String str1, final String str2) {
return Pattern.matches(" " + str1 + " (.*)", " " + str2 + " ");
}
Some tests:
String target = "part1 part2 part3 part4";
foo("part1 part2 part3 part4", target); // true
foo("part1 part2 part3", target); // true
foo("part1 part2", target); // true
foo("part1", target); // true
foo("part1 part3", target)); // false