Given a string S, find all the possible subsequences of the String in lexicographically-sorted order. I implemented in java but I am getting incorrect output. Please help
class Solution
{
public void helpr(String s,int ind,int n,StringBuilder curr,List<String> res){
if(ind==n){
res.add(curr.toString());
return;
}
helpr(s,ind+1,n,curr.append(s.charAt(ind)),res);
helpr(s,ind+1,n,curr,res);
}
public List<String> AllPossibleStrings(String s)
{
StringBuilder curr = new StringBuilder("");
List<String> res = new ArrayList<String>();
helpr(s,0,s.length(),curr,res);
Collections.sort(res);
res.remove(0);
return res;
}
}
for input - abc
actual op: abc abcc abcc abccbc abccbc abccbcc abccbcc
required op: a ab abc ac b bc c
import java.util.*;
class SubSequences {
static void get_sequence(String str, String ans, int i) {
// Base condition
if (i == str.length()) {
System.out.println("'" + ans + "'");
return;
}
// Before character gets added to final
get_sequence(str, ans, i + 1);
// after character gets added to ans
get_sequence(str, ans + str.charAt(i), i + 1);
}
public static void main(String arg[]) {
Scanner sc = new Scanner(System.in);
String str;
System.out.println("Enter the string");
str = sc.nextLine();
System.out.println("All possible subsequences are:");
get_sequence(str, "", 0);
}
}
Changed StringBuilder to String and its working now.
class Solution
{
public void helpr(String s,int ind,int n,String curr,List<String> res){
if(ind==n){
res.add(curr);
return;
}
helpr(s,ind+1,n,curr+s.charAt(ind),res);
helpr(s,ind+1,n,curr,res);
}
public List<String> AllPossibleStrings(String s)
{
String curr ="" ;
List<String> res = new ArrayList<String>();
helpr(s,0,s.length(),curr,res);
Collections.sort(res);
res.remove(0);
return res;
}
}
Related
For string s = "abcd" ,k=3 then answer should be:
abc
abd
acd
bcd
code by java with recursion(k=3) :
public class SubString {
static ArrayList<String> al = new ArrayList<>();
public static void main(String[] args) {
String s = "abcd";
findsubsequences(s, ""); // Calling a function
for (String subString : al) {
if (subString.length() == 3) {
System.out.println(subString);
}
}
}
public static void findsubsequences(String s, String ans) {
if (s.length() == 0) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0));
findsubsequences(s.substring(1), ans);
}
}
I want to Find all possible substring of length k in fastest way by recursion and without foreach in arraylist
Solution using backtracking logic (can be generalized to solve any permutation / subsets / combination problems) -
public static void main(String[] args) {
ans = new ArrayList<>();
String s = "abcd";
int k = 3;
generatePermutation(new StringBuilder(""), 0, s.toCharArray(), k);
System.out.println(ans);
}
private static List<String> ans;
private static void generatePermutation(StringBuilder temp, int st, char[] str, int k){
if(temp.length() == k){
// base result
String br = temp.toString();
ans.add(br);
return;
}
for(int i = st; i < str.length; i++){
temp.append(str[i]);
generatePermutation(temp, i + 1, str, k);
temp.setLength(temp.length() - 1);
}
}
Output :
[abc, abd, acd, bcd]
The faster / cleaner solution is to stop iterating when you reached the maximum length. And you should only add elements if the length is correct:
public static void findsubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return;
}
if (ans.length() == maxLength) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0), maxLength);
findsubsequences(s.substring(1), ans, maxLength);
}
Additionally you could get rid of the static result list ans instead return the results:
public static void main(String[] args) {
String s = "abcdefgh";
List<String> results = findSubsequences(s, "", 3);
for (String subString : results) {
System.out.println(subString);
}
}
public static List<String> findSubsequences(String s, String ans, int maxLength) {
if (s.length() == 0) {
return new ArrayList<>();
}
if (ans.length() == maxLength) {
return Collections.singletonList(ans);
}
List<String> list = new ArrayList<>(findSubsequences(s.substring(1), ans + s.charAt(0), maxLength));
list.addAll(findSubsequences(s.substring(1), ans, maxLength));
return list;
}
I am working on a program where we compare two strings and add the characters that are not present in one string to the other string and vice versa.
For example: String 1- aabccd
String 2- acccdd
The output should be- Characters to be added to String 1- cd
Characters to be added to String 2- ab
I am able to achieve it when the characters are not repeating,
For example: String 1- mango
String 2- anglo
The output is- Characters to be added to String 1- l
Characters to be added to String 2- m
but could not get it when the characters are repeating.
Here is the code that I have written-
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String S1, S2;
System.out.println("Enter String 1: ");
S1 = user_input.next();
System.out.println("Enter String 2: ");
S2 = user_input.next();
user_input.close();
char[] S1Array = S1.toLowerCase().toCharArray();
char[] S2Array = S2.toLowerCase().toCharArray();
charAddition(S1Array, S2Array);
charAdditionReverse(S2Array,S1Array);
}
private static void charAddition(char[] n, char[] S1Array) {
for (char n1 : n) {
if (!isPresent(n1, S1Array)) {
System.out.println("character to be added to S2Array
is: " + n1);
}
}
}
private static void charAdditionReverse(char[] n, char[] S1Array) {
for (char n1 : n) {
if (!isPresent(n1, S1Array)) {
System.out.println("character to be added to S1Array
is: " + n1);
}
}
}
private static boolean isPresent(char n, char[] S1Array) {
for (char i : S1Array) {
if (n == i) {
return true;
}
}
return false;
}
}
Here is your solution:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String S1, S2;
System.out.println("Enter String 1: ");
S1 = user_input.next();
System.out.println("Enter String 2: ");
S2 = user_input.next();
user_input.close();
char[] S1Array = S1.toLowerCase().toCharArray();
char[] S2Array = S2.toLowerCase().toCharArray();
charAddition(S1Array, S2Array,false);
charAddition(S2Array,S1Array,true);
}
private static void charAddition(char[] n, char[] S1Array,boolean isreverse)
{
List<char[]> asList = Arrays.asList(S1Array); // because this DOES compile.
List<Character> wordlist = new ArrayList<Character>();
for (char c : S1Array) {
wordlist.add(c);
}
for (char n1 : n)
{
if (!isPresent(n1, wordlist))
{
if(!isreverse)
{
System.out.println("character to be added to S2Arrayis: " + n1);
}else
{
System.out.println("character to be added to S1Arrayis: " + n1);
}
}
}
}
private static boolean isPresent(char n, List<Character> S1Array)
{
boolean flag ;
for (Iterator<Character> it = S1Array.iterator(); it.hasNext();)
{
char i = it.next();
if (n == i)
{
it.remove();
return true;
}
}
return false;
}
}
To solve above problem, you have to check how many times a specific character repeats. that's why I created new array list from array passed ArrayList to the function and removed the elements which are already matched. I have changed 2 function into one as i felt it is better way to write code.
A whole different approach:
void disjoint(String s1, String s2) {
// Convert two strings to character lists
List<Character> chars1 = s1.chars()
.mapToObj(t -> (char) t)
.collect(Collectors.toList());
List<Character> chars2 = s2.chars()
.mapToObj(t -> (char) t)
.collect(Collectors.toList());
// Make a list of elements we are going to remove from chars1
List<Character> removedElements = new ArrayList<>();
chars1.forEach(t -> {
// Try to remove the current character from chars2, and if it has
// successfully been removed, add it to our removedElements list
if (chars2.remove(t)) {
removedElements.add(t);
}
});
// At last remove each removed element from chars2 also from chars1
removedElements.forEach(chars1::remove);
System.out.println(chars1);
System.out.println(chars2);
}
I need your help in adding whitespace before a string as I need to format the String value to be in a specific position in the page. For example:
System.out.println(" Hello Word!!");
The above will give 10 spaces before the String which I did them manual, but is there any other way to specify the space before the String other than adding manual spaces?
Consider this as your code....
public static void main(String[] args) {
String hello = "hello";
Brute b = new Brute();
System.out.println( b.addspace(1,hello));
}
String addspace(int i, String str)
{
StringBuilder str1 = new StringBuilder();
for(int j=0;j<i;j++)
{
str1.append(" ");
}
str1.append(str);
return str1.toString();
}
This will add desired no of spaces in the string at its beginning...
Just pass your input String and no of spaces needed....
As addspace(<no_of_spaces>,<input_string>);
String newStr = String.format("%10s", str);
String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);
Result:
| Hello Word!!|
10 whitespaces added
You can write your own fumction:
public static void main(String[] args) {
String myString = "Hello Word!!";
System.out.println(getWhiteSpace(10)+myString);
}
private static String getWhiteSpace(int size) {
StringBuilder builder = new StringBuilder(size);
for(int i = 0; i <size ; i++) {
builder.append(' ');
}
return builder.toString();
}
This may be useful to you,
String s = "%s Hellow World!";
StringBuilder builder = new StringBuilder();
for(int i=0;i<10;i++){
builder.append(" ");
}
System.out.println(s.format(s,builder.toString()));
You can change the modify the count of space in the for loop.
import java.io.*;
import java.util.*;
class spaceBeforeString
{
public static void main(String args[])
{
String str="Hello";
for(int i=0;i<10;i++)
{
str=" "+str;
}
System.out.println(str);
}
}
import java.util.*;
import java.io.*;
class AddSpaceDemo
{
String str;
int noOfSpaces;
Scanner sc=new Scanner(System.in);
void getInput()
{
System.out.println("Enter the string before which the space is to be added: ");
str=sc.next();
System.out.println("Enter the no. of spaces to be added before the string: ");
noOfSpaces=sc.nextInt();
}
String addSpaceBefore()
{
for(int i=0;i<noOfSpaces;i++)
{
str=" "+str;
}
return str;
}
}
class AddSpace
{
public static void main(String args[])
{
String s;
AddSpaceDemo a=new AddSpaceDemo();
a.getInput();
s=a.addSpaceBefore();
System.out.println("String after adding whitespace before string: ");
System.out.println(s);
}
}
I'm making a basic Java POS System. You set how many characters fits on the paper width and it align both to the left and to the right.
public class Main {
int width = 32;
public static void main(String[] args) {
String dash = "--------------------------------";
String item = "COMPANY NAME";
String price = "00.00";
String string = alignment(item, price);
String description = "123-456-7890";
String tax = "0.00";
String string2 = alignment(description, tax);
System.out.println(dash);
System.out.println(string);
System.out.println(string2);
}
private static String alignment(String item, String price) {
String s = "";
s += item;
int x = 0;
while(x < width - item.length() - price.length()) {
s += " ";
x++;
}
s += price;
return s;
}
}
I hope this isn't a stupid question but I took the code below from another post. It just generates all permutations of a string. What I'd like to do is just modify it so all the permutations are added to an arraylist but I'm having some trouble finding what is hopefully the simple obvious solution. Can someone give this a quick look and explain what I'm doing wrong? I just want to take the permutations of a string and create an array list, that's all.
public class UserInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
List<String> inputList = new ArrayList<String>();
String input = scan.next();
permutation(input);
//Error occurs here
inputList.addAll(permutation(input));
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
Permutation has no return type, it is a void method, you are putting it in a list which only accepts objects of type String. You can modify it so once the recursion reaches the lowest level it adds itself to the list like so:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
List<String> inputList = new ArrayList<String>();
String input = scan.next();
permutation(input, inputList);
System.out.println(inputList);
}
public static void permutation(String str, List<String> result) {
permutation("", str, result);
}
private static void permutation(String prefix, String str,
List<String> container) {
int n = str.length();
if (n == 0) {
container.add(prefix);
} else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n),
container);
}
}
For "Hei"
[Hei, Hie, eHi, eiH, iHe, ieH]
Instead of printing the permutation out, you can add it to the list.
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class UserInput {
private static List<String> inputList;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word: ");
inputList = new ArrayList<>();
String input = scan.next();
permutation(input);
System.out.println(inputList.toString());
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) inputList.add(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
permutation(input) returns void, while inputList.addAll() expects Collection<String>.
I want to count the spaces in a string:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i =0,spaceCount=0;
while(i<word.length()){
char temp = word.charAt(i);
System.out.println(temp);
if(" ".equals(temp)){
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
When I replace the if statement with if(temp.equals(" ")), I get a "cannot invoke(String) on the primitive type char.
I don't understand why this won't work.
It won't work because you are calling a method of Class String (equals()) on a value which is of primitive type 'char'. You are trying to compare a 'char' with a 'String'.
You must compare between 'char's and since it's a primitive value you need to use '==' boolean compare operator like:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i = 0,
spaceCount = 0;
while( i < word.length() ){
if( word.charAt(i) == ' ' ) {
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
You can use the replace function for String to replace all the spaces(" ") with no spaces("") and get the difference between the lengths before and after calling the replace function.
Go through this example:
class Test{
public static void main(String args[]){
String s1 = "a b c";
int s1_length = s1.length();
System.out.println(s1_length); // 5
String s2 = s1.replace(" ","");
int s2_length = s2.length();
System.out.println(s2_length); // 3
System.out.println("No of spaces = " + (s1_length-s2_length)); // No of spaces = 2
}
}
You can use commons-lang.jar to calculate this.
`public class Main {
public static void main(String[] args) {
String word = "a b c";
System.out.println("Spaces in string: " + StringUtils.countMatches(word," "));
}
}`
The source of "StringUtils.countMatches" is below:
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
public class CountSpace {
public static void main(String[] args) {
String word = "a b c";
String data[];int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" ")){
k++;
}
}
System.out.println(k);
}
}