Find the longest String prefix [duplicate] - java

This question already has answers here:
Find longest common prefix?
(12 answers)
Closed 6 years ago.
Write a function to find the longest prefix of a list of string. For example,
['abc', 'abcde', 'abxyz'] => 'ab'
So it is an Arraylist and we find the longest prefix in the list of strings.
Let's try Java.
Please, no complete solutions
public string prefix (Arraylist<String> lst){
Arraylist<char[]> charLst = new Arraylist<>;
for(int i =0; i < lst.size(); i++){
charLst.add(lst.get(i).toCharArray());
}
}
But how do I proceed after creating a CharArray? This is already starting to be inefficient as it is O(n) with just the conversion to CharArray. I would just like some hint/help in the approach

Why do you add the ith character of every string to charLst? What you need is just the length of the longest common prefix, and then you can output the prefix based on the length you got.

Related

Java count how many times a char from string occurs from an array [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 5 years ago.
I'm new to java and I cant find the answer to this problem.
If I have two character arrays like this with counters:
Character[] abc = {'A','B','C'};
int countABC = 0;
Character[] def = {'D','E','F'};
int countDEF = 0;
And a string like this:
String something = "ABCDEFGHABAB";
How to increase the counters?
If you loop through each of the characters in the string and then within the loop use 2 'if' functions, one for each array then you can use the indexOf() function to search an array for that value. If the value is negative then it wasn't found and you don't increase the counter.
Here is some more info on indexOf():
https://www.tutorialspoint.com/java/java_string_indexof.htm

java split function. Store in an array from custom index? [duplicate]

This question already has answers here:
How I can index the array starting from 1 instead of zero?
(6 answers)
Closed 5 years ago.
I want to split a string and store in an array from custom index and NOT from "0" index by default.
Eg:
String splitThis = "cat,dog";
String [] array = splitThis.split(",");
System.out.println array[0] + array[1]
Above code prints "catdog" but I want "cat" to be store in index "1" and "dog" in index "2"
PS: I am very new to Programming and this is my very first question. Please correct me in syntax/logic/whatever :)
You may just add an empty entry at index 0. Something like this
String splitThis = "cat,dog";
String spit2 = ","+splitThis;
String [] array = split2.split(",");
System.out.println (array[1]);
System.out.println (array[2]);
You should probably create an entirely new class to handle that.

How to substring a String containing 4 bytes characters? [duplicate]

This question already has answers here:
How to get the substring that contains the first N unicode characters in Java
(2 answers)
Closed 5 years ago.
I have a String that could contain 4 bytes characters. For example:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
I also have a size that I should use to get a substring from it. The size is in characters. So let's say that size is 5, so I should get the first 4 bytes character along with "1234".
Directly using substring as s.substring(0, 5) gives the wrong result returning the first character and just "123".
I could manage to get the right result using code points this way:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
StringBuffer buf = new StringBuffer();
long size = 5;
s.codePoints().forEachOrdered(charInt -> {
if(buf.codePoints().count() < size) {
buf.appendCodePoint(charInt);
}
});
I bet there should be a way better and more efficient code to achieve this.
You can use offsetByCodePoints in order to help find the index of the character following 5 code points, and then use that as the second parameter to substring:
String s = "\uD83D\uDC4D1234\uD83D\uDC4D";
String sub = s.substring(0, s.offsetByCodePoints(0, 5));
Ideone Demo

count occurences of successive characters of a string [duplicate]

This question already has answers here:
Java compressing Strings
(21 answers)
Closed 7 years ago.
I have a String and I need to count occurances of successive characters of the string.
String s1="aabbcccaaa";
It should print output as
a2b2c3a3
String s1="aabbcccaaa";
char c[]=s1.toCharArray();
StringBuffer sb=new StringBuffer();
LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();
for(int i=0;i<c.length;i++)
{
Character c1=c[i];
Integer frequency=map.get(c1);
map.put(c1, (frequency==null)?1:frequency+1);
if(map.size()>1 && c[i]!=c[i-1])
{
sb.append(c[i-1]+""+map.get(c[i-1]));
map.remove(c[i-1]);
}
}
sb.append(map);
System.out.println(sb);
I am not sure how i can achieve counts if same elements occur again.
Hint #1: Test the current character against the previous one.
Hint #2: Ask yourself, why do you need to use a Map?

why running time of this code is 0(n^2) [duplicate]

This question already has answers here:
What is the complexity of this simple piece of code?
(10 answers)
Closed 8 years ago.
why running time of this code is O(n^2).(as written in cracking the coding interview book).and how it could be improved
public String makeSentence(String[] words) {
StringBuffer sentence = new StringBuffer();
for (String w : words) sentence.append(w);
return sentence.toString();
}
For n = the number of elements in the words array
The for loop means at least O(n)
Inside the for loop, each instance of sentence.append(w) should be "constant" since sentence is a StringBuffer.
Doing constant things n times means you get a total of O(n)
The key line to look at is for (String w : words) sentence.append(w);
In Java, a String append is an O(n) operation. Because the append is inside the for loop, the method as a whole is O(n^2).

Categories