when I create an array of Monomial by using Polynomial constructor,so sometimes
I get null object instead of Monomial object and sometimes I get the actual Monomial.
I don't understand why
I debug the code and in Polynomial constructor I construct the specific objects but when I return to the main method so sometimes I get the specific array of Monomial and sometimes I get a null in the a array.
TestPolynomials.java
public class TestPolynomials
{
public static void main(String[] args)
{
// 13b^2x^3z
Monomial m1 = new Monomial(13);
m1.setDegree('b', 2);
m1.setDegree('x', 3);
m1.setDegree('z', 1);
// 15
Monomial m2 = new Monomial(15);
Polynomial p1 = new Polynomial(new Monomial[] { m1, m2 });
}
}
Monomial.java
public class Monomial
{
private int coefficient;
private int[] var;
public Monomial(int coefficient)
{
this.coefficient = coefficient;
this.var = new int[26];
}
public int getCoefficient()
{
return coefficient;
}
public void setCoefficient(int coefficient)
{
this.coefficient = coefficient;
}
public int getDegree(char variable)
{
return var[variable - 'a'];
}
public void setDegree(char variable, int degree)
{
this.var[variable - 'a'] = degree;
}
public Monomial getCopy()
{
Monomial monom = new Monomial(this.coefficient);
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
monom.setDegree(ch, this.getDegree(ch));
}
return monom;
}
public String toString()
{
String monom = "";
monom += Integer.toString(this.getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
{
monom += ch;
if (this.getDegree(ch) > 1)
{
monom += "^";
monom += Integer.toString(this.getDegree(ch));
}
}
}
return monom;
}
}
Polynomial.java
public class Polynomial
{
private Monomial[] monomials;
public Polynomial(Monomial[] monomials)
{
this.monomials = new Monomial[monomials.length];
for (int i = 0; i < monomials.length; i++)
{
this.monomials[i] = monomials[i].getCopy();
}
}
public String toString()
{
String str = "";
for (int i = 0; i < this.getMonomialCount(); i++)
{
str += this.getMonomial(i).toString();
str += "+";
}
return str;
}
}
I construct m1 and m2 and I try to construct p1.
sometimes I get this: [13b^2x^3z, 15]and sometimes I get this:[null, 30]
Why?
Thanks.
========================================================================
edit:This is my full code,when I run it I get this in console
m1 = 13b^2x^3z
m2 = 15
m3 = -4b^2x^3z
m4 = 10b^3x^4z^2
13b^2x^3z does not have the same degrees as 15
13b^2x^3z has the same degrees as -4b^2x^3z
Exception in thread "main" java.lang.NullPointerException
at Polynomial.toString(Polynomial.java:98)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at TestPolynomials.main(TestPolynomials.java:44)
TestPolynomials.java
public class TestPolynomials
{
private static String tempstr = ""; // For printing results;
public static void main(String[] args)
{
// 13b^2x^3z
Monomial m1 = new Monomial(13);
m1.setDegree('b', 2);
m1.setDegree('x', 3);
m1.setDegree('z', 1);
System.out.println("m1 = " + m1);
// 15
Monomial m2 = new Monomial(15);
System.out.println("m2 = " + m2);
// -4b^2x^3z
Monomial m3 = new Monomial(-4);
m3.setDegree('b', 2);
m3.setDegree('x', 3);
m3.setDegree('z', 1);
System.out.println("m3 = " + m3);
Monomial m4 = new Monomial(10);
m4.setDegree('b', 3);
m4.setDegree('x', 4);
m4.setDegree('z', 2);
System.out.println("m4 = " + m4);
if (m1.hasSameDegrees(m2))
tempstr = " has";
else
tempstr = " does not have";
System.out.println(m1 + tempstr + " the same degrees as " + m2);
if (m1.hasSameDegrees(m3))
tempstr = " has";
else
tempstr = " does not have";
System.out.println(m1 + tempstr + " the same degrees as " + m3);
Polynomial p1 = new Polynomial(new Monomial[] { m1, m2 });
Polynomial p2 = new Polynomial(new Monomial[] { m3 });
Polynomial p3 = p1.add(p2);
System.out.println("p1 = " + p1); // should be 13b^2x^3z+15
System.out.println("p2 = " + p2); // should be -4b^2x^3z
System.out.println("p3 = " + p3); // should be 13b^2x^3z+15-4b^2x^3z up to reordering the monomials
System.out.println("-p3 = " + p3.inverse()); // should be -13b^2x^3z-15+4b^2x^3z up to reordering the monomials
System.out.println("p4 = p3 + p2");
Polynomial p4 = p3.add(p2);
int[] assignment = { 0, 1, 6, 4, 3, 0, 0, 2, 3, 5, 2, 6, 3, 8, 7, 0, 0, 4, 2, 6, 0, 4, 1, 5, 1, 9 };
System.out.println("p4 value = " + p4.computeValue(assignment) + " --- before normalization");
p4.normalize();
System.out.println("p4 = " + p4);
System.out.println("p4 value = " + p4.computeValue(assignment) + " --- after normalization");
Polynomial p5 = new Polynomial(new Monomial[] { m1, m2, m3, m4, m1, m2, m3, m4, m4 });
System.out.println("p5 items are m1,m2,m3,m4,m1,m2,m3,m4,m4");
System.out.println("p5 = " + p5);
Monomial m5 = new Monomial(0);
m5.setDegree('z', 1);
Polynomial p6 = new Polynomial(new Monomial[] { m5 });
System.out.println("p6 = " + p6);
Polynomial p7 = new Polynomial(new Monomial[] {});
System.out.println("p7 = " + p7);
}
}
Monomial.java
public class Monomial
{
private int coefficient;
private int[] var;
public Monomial(int coefficient)
{
this.coefficient = coefficient;
this.var = new int[26];
}
public int getCoefficient()
{
return coefficient;
}
public void setCoefficient(int coefficient)
{
this.coefficient = coefficient;
}
public int getDegree(char variable)
{
return var[variable - 'a'];
}
public void setDegree(char variable, int degree)
{
this.var[variable - 'a'] = degree;
}
public boolean hasSameDegrees(Monomial other)
{
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (!(this.getDegree(ch) == other.getDegree(ch)))
return false;
}
return true;
}
public Monomial getCopy()
{
Monomial monom = new Monomial(this.coefficient);
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
monom.setDegree(ch, this.getDegree(ch));
}
return monom;
}
public String toString()
{
String monom = "";
monom += Integer.toString(this.getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getDegree(ch) > 0)
{
monom += ch;
if (this.getDegree(ch) > 1)
{
monom += "^";
monom += Integer.toString(this.getDegree(ch));
}
}
}
return monom;
}
}
Polynomial.java
import java.lang.Math;
public class Polynomial
{
private Monomial[] monomials;
public Polynomial(Monomial[] monomials)
{
this.monomials = new Monomial[monomials.length];
for (int i = 0; i < monomials.length; i++)
{
this.monomials[i] = monomials[i].getCopy();
}
}
public int getMonomialCount()
{
return this.monomials.length;
}
public Monomial getMonomial(int index)
{
if (index <= this.getMonomialCount())
return this.monomials[index];
return null;
}
public Polynomial inverse()
{
Monomial[] inverse = new Monomial[this.getMonomialCount()];
for (int i = 0; i < inverse.length; i++)
{
inverse[i] = this.monomials[i].getCopy();
inverse[i].setCoefficient(inverse[i].getCoefficient() * -1);
}
return new Polynomial(inverse);
}
public Polynomial add(Polynomial other)
{
Monomial[] add = new Monomial[this.getMonomialCount() + other.getMonomialCount()];
for (int i = 0; i < other.getMonomialCount(); i++)
{
add[i] = other.getMonomial(i).getCopy();
}
for (int i = other.getMonomialCount(); i < add.length; i++)
{
add[i] = this.monomials[i - other.getMonomialCount()].getCopy();
}
return new Polynomial(add);
}
public int computeValue(int[] assignment)
{
int result = 1, sum = 0;
for (int i = 0; i < this.getMonomialCount(); i++)
{
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getMonomial(i).getDegree(ch) > 0)
result *= (int) Math.pow((double) assignment[i], (double) this.getMonomial(i).getDegree(ch));
}
result *= this.getMonomial(i).getCoefficient();
sum += result;
result = 1;
}
return sum;
}
public void normalize()
{
Monomial[] normalize = new Monomial[this.getMonomialCount()];
for (int i = 0; i < this.getMonomialCount(); i++)
{
for (int j = 1; j < this.getMonomialCount(); j++)
{
if (this.getMonomial(i).hasSameDegrees(this.getMonomial(j)))
{
normalize[i] = new Monomial(this.getMonomial(i).getCoefficient() + this.getMonomial(j).getCoefficient());
for (char ch = 'a'; ch <= 'z'; ch++)
{
if (this.getMonomial(i).getDegree(ch) > 0)
normalize[i].setDegree(ch, this.getMonomial(i).getDegree(ch));
}
this.monomials[i] = null;
}
}
}
this.monomials = normalize;
}
public String toString()
{
normalize();
String str = "";
for (int i = 0; i < this.getMonomialCount(); i++)
{
str += this.getMonomial(i).toString();
str += "+";
}
return str;
}
}
Why??
I have a project that I need to have its jar file , but it doesn't open , can anyone help me please, I need it as soon as possible for my university . And here is the whole code :
package huffmanproject;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class huffmanproject {
public static class HuffNode implements Comparable<HuffNode> {
public int value;
public int weight;
public HuffNode leftTree;
public HuffNode rightTree;
public HuffNode parent;
public HuffNode() {
parent = null;
}
public HuffNode( int v, int w, HuffNode lTree, HuffNode rTree, HuffNode par ) {
value = v;
weight = w;
leftTree = lTree;
rightTree = rTree;
parent = par;
}
#Override
public int compareTo(HuffNode rhs) {
return weight - rhs.weight;
}
#Override
public String toString() {
String str = "";
str += this.value;
return str;
}
}
public static class HuffTree {
private int size = 0;
private HuffNode root = new HuffNode();
private PriorityQueue<HuffNode> huffQueue = new PriorityQueue();
public ArrayList<String> pathTable = new ArrayList();
public ArrayList<Character> valueTable = new ArrayList();
public HuffTree(int[] freq, char[] code) {
this.size = freq.length;
if (freq.length != code.length) {
throw new UnsupportedOperationException("Error: Character and code length mismatch.");
}
for (int i = 0; i < this.size; i++) {
huffQueue.offer(new HuffNode(code[i], freq[i], null, null, null));
}
createTree();
createTable(this.root, "");
}
private void createTree() {
while (huffQueue.size() > 1) {
HuffNode tempL = huffQueue.poll();
HuffNode tempR = huffQueue.poll();
HuffNode parent = new HuffNode(0, tempL.weight+tempR.weight, tempL, tempR, null);
tempL.parent = parent;
tempR.parent = parent;
huffQueue.offer(parent);
this.size++;
}
this.root = huffQueue.peek();
}
private void createTable(HuffNode curr, String str) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
char tempChar;
if (curr.value == 32)
tempChar = ' ';
if (curr.value == 10)
tempChar = 'n';
else
tempChar = (char)curr.value;
this.valueTable.add(tempChar);
this.pathTable.add(str);
}
str += "0";
createTable(curr.leftTree, str);
str = str.substring(0, str.length()-1);
str += "1";
createTable(curr.rightTree, str);
}
String tacks = "";
public void getTree(HuffNode curr) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
switch (curr.value) {
case 32:
System.out.println(tacks + curr.weight + ": sp");
break;
case 10:
System.out.println(tacks + curr.weight + ": nl");
break;
default:
System.out.println(tacks + curr.weight + ": " + (char)curr.value);
break;
}
}
else
System.out.println(tacks + curr.weight);
tacks += "- ";
getTree(curr.leftTree);
getTree(curr.rightTree);
tacks = tacks.substring(0, tacks.length()-2);
}
public int getSize() { return this.size; }
public String encode(String input){
String str = "";
for (int x = 0; x < input.length(); x++) {
for (int i = 0; i < valueTable.size(); i++) {
if (valueTable.get(i) == input.charAt(x))
str += pathTable.get(i);
}
}
return str;
}
public String decode(String bits) {
String decodedStr = "";
for (int i = 0; i < bits.length(); i++) {
if (!getChar(bits.substring(0, i+1)).equals("")) {
decodedStr += getChar(bits.substring(0, i+1));
bits = bits.substring(i+1);
i = 0;
}
}
return decodedStr;
}
private String getChar(String bits) {
String character = "";
for (int i = 0; i < pathTable.size(); i++) {
if (pathTable.get(i).equals(bits))
character = valueTable.get(i).toString();
}
return character;
}
}
public static void main(String[] args) {
// for example assume that we have these letters with these different frequencies like below:
int freq[] = {10, 15, 12, 3, 4, 13, 1};
char code[] = {'a', 'e', 'i', 's', 't', ' ', '\n'};
HuffTree hTree = new HuffTree(freq, code);
System.out.println("Display Tree:");
HuffNode curr = hTree.root;
hTree.getTree(curr);
System.out.println("");
// and we want to build the huffman tree of the word sea :
System.out.println("Encode 'sea': " + hTree.encode("sea") +"\n");
System.out.println("Decode '" + hTree.encode("sea") + "': " + hTree.decode(hTree.encode("tea")));
}
}
If it's simply not compiling into a jar file, try the following command in command prompt or terminal.
jar cf jar-file input-file(s)
From Oracle: Creating jar File
To open command prompt, use WIN+R to open the run box, type cmd, and press enter.
navigate to the directory of your java file:
cd C:\Path\to\my\java\file\HuffNode.java
run the command:
jar cf HuffNode.jar HuffNode.java
If you have multiple .java files:
jar cf HuffNode.jar File1.java File2.java File3.java
I m writing a method to find the first non repeating character in a string. I saw this method in a previous stackoverflow question
public static char findFirstNonRepChar(String input){
char currentChar = '\0';
int len = input.length();
for(int i=0;i<len;i++){
currentChar = input.charAt(i);
if((i!=0) && (currentChar!=input.charAt(i-1)) && (i==input.lastIndexOf(currentChar))){
return currentChar;
}
}
return currentChar;
}
I came up with a solution using a hashtable where I have two for loops (not nested) where I interate through the string in one loop writing down each occurance of a letter (for example in apple, a would have 1, p would have 2, etc.) then in the second loop I interate through the hashtable to see which one has a count of 1 first. What is the benefit to the above method over what I came up with? I am new to Java does having two loops (not nested) hinder time complexity. Both these algorithms should have O(n) right? Is there another faster, less space complexity algorithm for this question than these two solutions?
public class FirstNonRepeatCharFromString {
public static void main(String[] args) {
String s = "java";
for(Character ch:s.toCharArray()) {
if(s.indexOf(ch) == s.lastIndexOf(ch)) {
System.out.println("First non repeat character = " + ch);
break;
}
}
}
}
As you asked if your code is from O(n) or not, I think it's not, because in the for loop, you are calling lastIndexOf and it's worst case is O(n). So it is from O(n^2).
About your second question: having two loops which are not nested, also makes it from O(n).
If assuming non unicode characters in your input String, and Uppercase or Lowercase characters are assumed to be different, the following would do it with o(n) and supports all ASCII codes from 0 to 255:
public static Character getFirstNotRepeatedChar(String input) {
byte[] flags = new byte[256]; //all is initialized by 0
for (int i = 0; i < input.length(); i++) { // O(n)
flags[(int)input.charAt(i)]++ ;
}
for (int i = 0; i < input.length(); i++) { // O(n)
if(flags[(int)input.charAt(i)] > 0)
return input.charAt(i);
}
return null;
}
Thanks to Konstantinos Chalkias hint about the overflow, if your input string has more than 127 occurrence of a certain character, you can change the type of flags array from byte[] to int[] or long[] to prevent the overflow of byte type.
Hope it would be helpful.
The algorithm you showed is slow: it looks for each character in the string, it basically means that for each character you spend your time checking the string twice!! Huge time loss.
The best naive O(n) solution basically holds all the characters in order of insertion (so the first can be found) and maps a mutable integer to them. When we're done, analyzing, we go through all the entries and return the first character that was registered and has a count of 1.
There are no restrictions on the characters you can use. And AtomicInteger is available with import java.util.concurrent.atomic.AtomicInteger.
Using Java 8:
public static char findFirstNonRepChar(String string) {
Map<Integer,Long> characters = string.chars().boxed()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
return (char)(int)characters.entrySet().stream()
.filter(e -> e.getValue() == 1L)
.findFirst()
.map(Map.Entry::getKey)
.orElseThrow(() -> new RuntimeException("No unrepeated character"));
}
Non Java 8 equivalent:
public static char findFirstNonRepChar(String string) {
Map<Character, AtomicInteger> characters = new LinkedHashMap<>(); // preserves order of insertion.
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
AtomicInteger n = characters.get(c);
if (n == null) {
n = new AtomicInteger(0);
characters.put(c, n);
}
n.incrementAndGet();
}
for (Map.Entry<Character, AtomicInteger> entry: characters.entries()) {
if (entry.getValue().get() == 1) {
return entry.getKey();
}
}
throw new RuntimeException("No unrepeated character");
}
import java.util.LinkedHashMap;
import java.util.Map;
public class getFirstNonRep {
public static char get(String s) throws Exception {
if (s.length() == 0) {
System.out.println("Fail");
System.exit(0);
} else {
Map<Character, Integer> m = new LinkedHashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
if (m.containsKey(s.charAt(i))) {
m.put(s.charAt(i), m.get(s.charAt(i)) + 1);
} else {
m.put(s.charAt(i), 1);
}
}
for (Map.Entry<Character, Integer> hm : m.entrySet()) {
if (hm.getValue() == 1) {
return hm.getKey();
}
}
}
return 0;
}
public static void main(String[] args) throws Exception {
System.out.print(get("Youssef Zaky"));
}
}
This solution takes less space and less time, since we iterate the string only one time.
Works for any type of characters.
String charHolder; // Holds
String testString = "8uiuiti080t8xt8t";
char testChar = ' ';
int count = 0;
for (int i=0; i <= testString.length()-1; i++) {
testChar = testString.charAt(i);
for (int j=0; j < testString.length()-1; j++) {
if (testChar == testString.charAt(j)) {
count++;
}
}
if (count == 1) { break; };
count = 0;
}
System.out.println("The first not repeating character is " + testChar);
I accumulated all possible methods with string length 25'500 symbols:
private static String getFirstUniqueChar(String line) {
String result1 = null, result2 = null, result3 = null, result4 = null, result5 = null;
int length = line.length();
long start = System.currentTimeMillis();
Map<Character, Integer> chars = new LinkedHashMap<Character, Integer>();
char[] charArray1 = line.toCharArray();
for (int i = 0; i < length; i++) {
char currentChar = charArray1[i];
chars.put(currentChar, chars.containsKey(currentChar) ? chars.get(currentChar) + 1 : 1);
}
for (Map.Entry<Character, Integer> entry : chars.entrySet()) {
if (entry.getValue() == 1) {
result1 = entry.getKey().toString();
break;
}
}
long end = System.currentTimeMillis();
System.out.println("1st test:\n result: " + result1 + "\n time: " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
String current = Character.toString(line.charAt(i));
String left = line.substring(0, i);
if (!left.contains(current)) {
String right = line.substring(i + 1);
if (!right.contains(current)) {
result2 = current;
break;
}
}
}
end = System.currentTimeMillis();
System.out.println("2nd test:\n result: " + result2 + "\n time: " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
char currentChar = line.charAt(i);
if (line.indexOf(currentChar) == line.lastIndexOf(currentChar)) {
result3 = Character.toString(currentChar);
break;
}
}
end = System.currentTimeMillis();
System.out.println("3rd test:\n result: " + result3 + "\n time: " + (end - start));
start = System.currentTimeMillis();
char[] charArray4 = line.toCharArray();
for (int i = 0; i < length; i++) {
char currentChar = charArray4[i];
int count = 0;
for (int j = 0; j < length; j++) {
if (currentChar == charArray4[j] && i != j) {
count++;
break;
}
}
if (count == 0) {
result4 = Character.toString(currentChar);
break;
}
}
end = System.currentTimeMillis();
System.out.println("4th test:\n result: " + result4 + "\n time: " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
char currentChar = line.charAt(i);
int count = 0;
for (int j = 0; j < length; j++) {
if (currentChar == line.charAt(j) && i != j) {
count++;
break;
}
}
if (count == 0) {
result5 = Character.toString(currentChar);
break;
}
}
end = System.currentTimeMillis();
System.out.println("5th test:\n result: " + result5 + "\n time: " + (end - start));
return result1;
}
And time results (5 times):
1st test:
result: g
time: 13, 12, 12, 12, 14
2nd test:
result: g
time: 55, 56, 59, 70, 59
3rd test:
result: g
time: 2, 3, 2, 2, 3
4th test:
result: g
time: 3, 3, 2, 3, 3
5th test:
result: g
time: 6, 5, 5, 5, 6
public static char NonReapitingCharacter(String str) {
Set<Character> s = new HashSet();
char ch = '\u0000';
for (char c : str.toCharArray()) {
if (s.add(c)) {
if (c == ch) {
break;
} else {
ch = c;
}
}
}
return ch;
}
Okay I misread the question initially so here's a new solution. I believe is this O(n). The contains(Object) of HashSet is O(1), so we can take advantage of that and avoid a second loop. Essentially if we've never seen a specific char before, we add it to the validChars as a potential candidate to be returned. The second we see it again however, we add it to the trash can of invalidChars. This prevents that char from being added again. At the end of the loop (you have to loop at least once no matter what you do), you'll have a validChars hashset with n amount of elements. If none are there, then it will return null from the Character class. This has a distinct advantage as the char class has no good way to return a 'bad' result so to speak.
public static Character findNonRepeatingChar(String x)
{
HashSet<Character> validChars = new HashSet<>();
HashSet<Character> invalidChars = new HashSet<>();
char[] array = x.toCharArray();
for (char c : array)
{
if (validChars.contains(c))
{
validChars.remove(c);
invalidChars.add(c);
}
else if (!validChars.contains(c) && !invalidChars.contains(c))
{
validChars.add(c);
}
}
return (!validChars.isEmpty() ? validChars.iterator().next() : null);
}
If you are only interested for characters in the range a-z (lowercase as OP requested in comments), you can use this method that requires a minimum extra storage of two bits per character Vs a HashMap approach.
/*
* It works for lowercase a-z
* you can scale it to add more characters
* eg use 128 Vs 26 for ASCII or 256 for extended ASCII
*/
public static char getFirstNotRepeatedChar(String input) {
boolean[] charsExist = new boolean[26];
boolean[] charsNonUnique = new boolean[26];
for (int i = 0; i < input.length(); i++) {
int index = 'z' - input.charAt(i);
if (!charsExist[index]) {
charsExist[index] = true;
} else {
charsNonUnique[index] = true;
}
}
for (int i = 0; i < input.length(); i++) {
if (!charsNonUnique['z' - input.charAt(i)])
return input.charAt(i);
}
return '?'; //example return of no character found
}
In case of two loops (not nested) the time complexity would be O(n).
The second solution mentioned in the question can be implemented as:
We can use string characters as keys to a map and maintain their count. Following is the algorithm.
1.Scan the string from left to right and construct the count map.
2.Again, scan the string from left to right and check for count of each character from the map, if you find an element who’s count is 1, return it.
package com.java.teasers.samples;
import java.util.Map;
import java.util.HashMap;
public class NonRepeatCharacter {
public static void main(String[] args) {
String yourString = "Hi this is javateasers";//change it with your string
Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
//Step 1 of the Algorithm
for (int i = 0; i < yourString.length(); i++) {
Character character = yourString.charAt(i);
//check if character is already present
if(null != characterMap.get(character)){
//in case it is already there increment the count by 1.
characterMap.put(character, characterMap.get(character) + 1);
}
//in case it is for the first time. Put 1 to the count
else
characterMap.put(character, 1);
}
//Step 2 of the Algorithm
for (int i = 0; i < yourString.length(); i++) {
Character character = yourString.charAt(i);
int count = characterMap.get(character);
if(count == 1){
System.out.println("character is:" + character);
break;
}
}
}
}
public char firstNonRepeatedChar(String input) {
char out = 0;
int length = input.length();
for (int i = 0; i < length; i++) {
String sub1 = input.substring(0, i);
String sub2 = input.substring(i + 1);
if (!(sub1.contains(input.charAt(i) + "") || sub2.contains(input
.charAt(i) + ""))) {
out = input.charAt(i);
break;
}
}
return out;
}
Since LinkedHashMap keeps the order of insertion
package com.company;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
String l = sc.nextLine();
System.out.println(firstCharNoRepeated(l));
}
private static String firstCharNoRepeated(String l) {
Map<String, Integer> chars = new LinkedHashMap();
for(int i=0; i < l.length(); i++) {
String c = String.valueOf(l.charAt(i));
if(!chars.containsKey(c)){
chars.put(c, i);
} else {
chars.remove(c);
}
}
return chars.keySet().iterator().next();
}
}
Few lines of code, works for me.
public class FirstNonRepeatingCharacter {
final static String string = "cascade";
public static void main(String[] args) {
char[] charArr = string.toCharArray();
for (int i = 0; charArr.length > i; i++) {
int count = 0;
for (int j = 0; charArr.length > j; j++) {
if (charArr[i] == charArr[j]) {
count++;
}
}
if (count == 1){
System.out.println("First Non Repeating Character is: " + charArr[i]);
break;
}
}
}
}
Constraint for this solution:
O(n) time complexity. My solution is O(2n), follow Time Complexity analysis,O(2n) => O(n)
import java.util.HashMap;
public class FindFirstNonDuplicateCharacter {
public static void main(String args[]) {
System.out.println(findFirstNonDuplicateCharacter("abacbcefd"));
}
private static char findFirstNonDuplicateCharacter(String s) {
HashMap<Character, Integer> chDupCount = new HashMap<Character, Integer>();
char[] charArr = s.toCharArray();
for (char ch: charArr) { //first loop, make the tables and counted duplication by key O(n)
if (!chDupCount.containsKey(ch)) {
chDupCount.put(ch,1);
continue;
}
int dupCount = chDupCount.get(ch)+1;
chDupCount.replace(ch, dupCount);
}
char res = '-';
for(char ch: charArr) { //second loop, get the first duplicate by count number, O(2n)
// System.out.println("key: " + ch+", value: " + chDupCount.get(ch));
if (chDupCount.get(ch) == 1) {
res = ch;
break;
}
}
return res;
}
}
Hope it help
char firstNotRepeatingCharacter(String s) {
for(int i=0; i< s.length(); i++){
if(i == s.lastIndexOf(s.charAt(i)) && i == s.indexOf(s.charAt(i))){
return s.charAt(i);
}
}
return '_';
}
String a = "sampapl";
char ar[] = a.toCharArray();
int dya[] = new int[256];
for (int i = 0; i < dya.length; i++) {
dya[i] = -1;
}
for (int i = 0; i < ar.length; i++) {
if (dya[ar[i]] != -1) {
System.out.println(ar[i]);
break;
} else {
dya[ar[i]] = ar[i];
}
}
This is solution in python:
input_str = "interesting"
#input_str = "aabbcc"
#input_str = "aaaapaabbcccq"
def firstNonRepeating(param):
counts = {}
for i in range(0, len(param)):
# Store count and index repectively
if param[i] in counts:
counts[param[i]][0] += 1
else:
counts[param[i]] = [1, i]
result_index = len(param) - 1
for x in counts:
if counts[x][0] == 1 and result_index > counts[x][1]:
result_index = counts[x][1]
return result_index
result_index = firstNonRepeating(input_str)
if result_index == len(input_str)-1:
print("no such character found")
else:
print("first non repeating charater found: " + input_str[result_index])
Output:
first non repeating charater found: r
import java.util.*;
public class Main {
public static void main(String[] args) {
String str1 = "gibblegabbler";
System.out.println("The given string is: " + str1);
for (int i = 0; i < str1.length(); i++) {
boolean unique = true;
for (int j = 0; j < str1.length(); j++) {
if (i != j && str1.charAt(i) == str1.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
System.out.println("The first non repeated character in String is: " + str1.charAt(i));
break;
}
}
}
}
public class GFG {
public static void main(String[] args) {
String s = "mmjjjjmmn";
for (char c : s.toCharArray()) {
if (s.indexOf(c) == s.lastIndexOf(c)) {
System.out.println("First non repeated is:" + c);
break;
}
}
}
output = n
Non Repeated Character String in Java
public class NonRepeatedCharacter {
public static void main(String[] args) {
String s = "ffeeddbbaaclck";
for (int i = 0; i < s.length(); i++) {
boolean unique = true;
for (int j = 0; j < s.length(); j++) {
if (i != j && s.charAt(i) == s.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
System.out.println("First non repeated characted in String \""
+ s + "\" is:" + s.charAt(i));
break;
}
}
}
}
Output:
First non repeated characted in String "ffeeddbbaaclck" is:l
For More Details
In this coding i use length of string to find the first non repeating letter.
package com.string.assingment3;
import java.util.Scanner;
public class FirstNonRepetedChar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String : ");
String str = in.next();
char[] ch = str.toCharArray();
int length = ch.length;
int x = length;
for(int i=0;i<length;i++) {
x = length-i;
for(int j=i+1;j<length;j++) {
if(ch[i]!=ch[j]) {
x--;
}//if
}//inner for
if(x==1) {
System.out.println(ch[i]);
break;
}
else {
continue;
}
}//outer for
}
}// develope by NDM
In Kotlin
fun firstNonRepeating(string: String): Char?{
//Get a copy of the string
var copy = string
//Slice string into chars then convert them to string
string.map { it.toString() }.forEach {
//Replace first occurrance of that character and check if it still has it
if (copy.replaceFirst(it,"").contains(it))
//If it has the given character remove it
copy = copy.replace(it,"")
}
//Return null if there is no non-repeating character
if (copy.isEmpty())
return null
//Get the first character from what left of that string
return copy.first()
}
https://pl.kotl.in/KzL-veYNZ
public static void firstNonRepeatFirstChar(String str) {
System.out.println("The given string is: " + str);
for (int i = 0; i < str.length(); i++) {
boolean unique = true;
for (int j = 0; j < str.length(); j++) {
if (i != j && str.charAt(i) == str.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
System.out.println("The first non repeated character in String is: " + str.charAt(i));
break;
}
}
}
Using Set with single for loop
public static Character firstNonRepeatedCharacter(String str) {
Character result = null;
if (str != null) {
Set<Character> set = new HashSet<>();
for (char c : str.toCharArray()) {
if (set.add(c) && result == null) {
result = c;
} else if (result != null && c == result) {
result = null;
}
}
}
return result;
}
You can achieve this in single traversal of String using LinkedHashSet as follows:
public static Character getFirstNonRepeatingCharacter(String str) {
Set<Character> result = new LinkedHashSet<>(256);
for (int i = 0; i< str.length(); ++i) {
if(!result.add(str.charAt(i))) {
result.remove(str.charAt(i));
}
}
if(result.iterator().hasNext()) {
return result.iterator().next();
}
return null;
}
For Java;
char firstNotRepeatingCharacter(String s) {
HashSet<String> hs = new HashSet<>();
StringBuilder sb =new StringBuilder(s);
for (int i = 0; i<s.length(); i++){
char c = sb.charAt(i);
if(s.indexOf(c) == i && s.indexOf(c, i+1) == -1 ) {
return c;
}
}
return '_';
}
public class FirstNonRepeatingChar {
public static void main(String[] args) {
String s = "hello world i am here";
s.chars().boxed()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() == 1).findFirst().ifPresent(e->System.out.println(e.getKey()));
}
}
package looping.concepts;
import java.util.Scanner;
public class Line {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String a = sc.nextLine();
int i = 0;
int j = 0;
for (i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
int counter = 0;
// boolean repeat = false;
for (j = 0; j < a.length(); j++) {
if (ch == a.charAt(j)) {
counter++;
}
}
if (counter == 1) {
System.out.print(ch);
}
else
{
System.out.print("There is no non repeated character");
break;
}
}
}
}
import java.util.Scanner;
public class NonRepaeated1
{
public static void main(String args[])
{
String str;
char non_repeat=0;
int len,i,j,count=0;
Scanner s = new Scanner(System.in);
str = s.nextLine();
len = str.length();
for(i=0;i<len;i++)
{
non_repeat=str.charAt(i);
count=1;
for(j=0;j<len;j++)
{
if(i!=j)
{
if(str.charAt(i) == str.charAt(j))
{
count=0;
break;
}
}
}
if(count==1)
break;
}
if(count == 1)
System.out.print("The non repeated character is : " + non_repeat);
}
}
package com.test.util;
public class StringNoRepeat {
public static void main(String args[]) {
String st = "234123nljnsdfsdf41l";
String strOrig=st;
int i=0;
int j=0;
String st1="";
Character ch=' ';
boolean fnd=false;
for (i=0;i<strOrig.length(); i++) {
ch=strOrig.charAt(i);
st1 = ch.toString();
if (i==0)
st = strOrig.substring(1,strOrig.length());
else if (i == strOrig.length()-1)
st=strOrig.substring(0, strOrig.length()-1);
else
st=strOrig.substring(0, i)+strOrig.substring(i+1,strOrig.length());
if (st.indexOf(st1) == -1) {
fnd=true;
j=i;
break;
}
}
if (!fnd)
System.out.println("The first no non repeated character");
else
System.out.println("The first non repeated character is " +strOrig.charAt(j));
}
}
Just like older mobile phones' keypads work. I should input a string of numbers and the program should print out a text based on those numbers.
e.g: Input: 4448 9666777557777 should output to: ITWORKS.
Here's my code so far but it's not printing out anything. Could you please tell me what's wrong with it and what could've I done better?
Scanner sc = new Scanner(System.in);
String[] letters = {
"0",
"1",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ"
};
System.out.println("Write something.");
String numbers = sc.nextLine();
char[] toChar = numbers.toCharArray();
int count = 0;
for (int index = 0; index < toChar.length; index++) {
if (toChar[index] >= '2' && toChar[index] <= '9') {
if (index > 0 && toChar[index] == toChar[index - 1]) {
count++;
}
else if (count > 0) {
System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
count = 0;
}
}
}
How about this?
import java.util.Scanner;
public class Test {
private static final String[] letters = {
"0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};
private static char getChar(int digit, int count) {
while (count > letters[digit].length()) {
count -= letters[digit].length();
}
return letters[digit].charAt(count - 1);
}
private static String getString(String input) {
int lastDigit = 0, count = 1;
String result = "";
for (int i = 0; i < input.length(); i++) {
int currentDigit = input.charAt(i) - '0';
if (currentDigit >= 2 && currentDigit <= 9) {
if (lastDigit == 0) {
lastDigit = currentDigit;
} else if (currentDigit == lastDigit) {
count++;
} else {
result += getChar(lastDigit, count);
lastDigit = currentDigit;
count = 1;
}
}
}
return result + getChar(lastDigit, count);
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Write something");
System.out.println(getString(scanner.nextLine()));
}
}
}
I enhanced the problem decomposition. It works for all examples OP has shown so far.
If I understand your intention correctly, count should increment only if current digit is the same as previous:
for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {
int n = letters[c - '0'].length;
while (pos < toChar.length && c == toChar[pos] && count < n) {
pos++;
count++;
}
System.out.println(letters[c - '0'].charAt(count - 1));
if (pos < toChar.length - 1) {
c = toChar[++pos];
}
}
This code will help you!
Check this one
public class Denene {
public static String getChar(String cha)
{
String [] chars= {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
String[] strSplit = cha.split(" "); //7777 88 7777 2 66 8
int len=strSplit.length;
char r;
char []ar =new char[len];
for(int i=0;i<len;i++){
String str=strSplit[i];
ar[i]= chars[Integer.parseInt(String.valueOf(str.charAt(0)))].charAt(str.length()-1);
}
return new String(ar);
}
public static void main(String[] args) {
System.out.println("Enter any number .....");
System.out.println(getChar(new Scanner(System.in).nextLine())); //Output : susant
}
}
i have two strings s1 and s2 and i would like to sort s2 based on the order of appearance of letters in s1 and if other alphabets are left in s2 sort them alphabetically.
Assume i have the following;
String s1 = "war";
String s2 = "Its awesome being a programmer";
output: waaarrrIbeeeeggimmmnoopsst.
I have written a code to do that already though buut i was wondering if its possible using the comparator/comparable interface to solve it.
Listed below is my code snippet.
public class Sort {
private static String a = "war";
private static String b = "Its awesome being a programmer";
static List<Character> list = new ArrayList<>();
static public void main(String[] args) {
Character s;
Character x;
System.out.println("String to be sorted: '" + b + "'");
System.out.println("Key for sort: '" + a + "'");
/*
* put all the string in a list
*/
for (int i = 0; i < b.length(); i++) {
s = b.charAt(i);
if (s != ' ') {
list.add(s);
}
}
/*
* compare individual chac in key with individaul char in string to sort
*/
StringBuilder sb = new StringBuilder();
for (int j = 0; j < a.length(); j++) {
x = a.charAt(j);
for (int k = 0; k < b.length(); k++) {
s = b.charAt(k);
if (x == s) {
sb.append(s);
list.remove(x);
}
}
}
/*
* check if list is empty if not, sort and append the rest to the stringbuilder
*/
if (!list.isEmpty()) {
Collections.sort(list);
for (char c : list) {
sb.append(c);
}
}
System.out.println("Sorted version of string: '" + sb.toString() + "'");
}
}
private static String a = "war";
private static String b = "Its awesome being a programmer".replace(" ","");
private static String answer = "waaarrrIbeeeeggimmmnoopsst";
public static void main(String[] args) {
List<String> characters = new ArrayList<String>(b.length());
for (int i=0;i<b.length();i++){
characters.add(String.valueOf(b.charAt(i)));
}
Collections.sort(characters,new CompareIt(a));
String sortedString = listToString(characters);
System.out.println(sortedString);
System.out.println(answer);
System.out.println(answer.equals(sortedString));
}
private static String listToString(List<String> listOfStrings){
StringBuilder builder = new StringBuilder();
for (String str : listOfStrings){
builder.append(str);
}
return builder.toString();
}
private static class CompareIt implements Comparator<String>{
private final String source;
public CompareIt(String source) {
super();
this.source = source;
}
public int compare(String o1, String o2) {
int i1 = source.indexOf(o1);
int i2 = source.indexOf(o2);
if (i1==-1 && i2!=-1){
return 1;
} else if (i1!=-1 && i2==-1){
return -1;
} else if (i1!=-1 && i2!=-1){
return i1 > i2 ? 1:-1;
} else {
return o1.compareTo(o2);
}
}
}
This seems to work.
EDITED: To include sysout that result matches expected answer provided in question.
EDIT2: Typo with final indexed comparison I had ? 1:0 instead of 1:-1.
public static void main(String[] args) {
String s1 = "war";
String s2 = "Its awesome being a programmer";
String result = "";
for (int i = 0; i < s1.length(); i++) {
int len = s2.length()
- s2.replace(String.valueOf(s1.charAt(i)), "").length();
s2 = s2.replace(String.valueOf(s1.charAt(i)), "").replace(" ", "");
for (int j = 0; j < len; j++)
result = result + String.valueOf(s1.charAt(i));
}
char[] remaining = s2.toCharArray();
Arrays.sort(remaining);
for (Character c : remaining)
result = result + String.valueOf(c);
System.out.println(result);
}
Try this: I tried without using any interface.
Output:
waaarrrIbeeeeggimmmnoopsst
public static Comparator<Character> compareOn(final String key) {
return new Comparator<Character>() {
public int compare(Character c1, Character c2) {
final int indexInKey1 = key.indexOf(c1);
final int indexInKey2 = key.indexOf(c2);
final int result;
if (indexInKey1 == -1 && indexInKey2 == -1) {
result = c1.compareTo(c2); //fall back to natural ordering
} else {
if (indexInKey1 == -1) {
result = 1;
} else if (indexInKey2 == -1) {
result = -1;
} else {
result = indexInKey1 - indexInKey2;
}
}
return result;
}
};
}
public static void main(String[] args) {
final String a = "war";
final String b = "Its awesome being a programmer";
final List<Character> chars = new ArrayList<Character>();
for (char c: b.toCharArray()) {
if (c != ' ') {
chars.add(c);
}
}
Collections.sort(chars, compareOn(a));
System.out.println(chars);
}