Leetcode longest common prefix [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 3 months ago.
Improve this question
I am having a hard time following this solution. I understand we set a prefix, and loop through the remainder of the array and keep chopping the prefix until prefix fully exists in each string but why are we doing strs[i].indexOf(output) != 0 in the while loop?
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) {
return "";
}
String output = strs[0];
for(int i = 1; i < strs.length; i++) {
while(strs[i].indexOf(output) != 0) {
output = output.substring(0, output.length() - 1);
}
}
return output;
}

Much more understandable (and efficient) would be to use "not startWith."
while (!strs[i].startsWith(output)) {
output = output.substring(0, output.length() - 1);
}
indexOf would also search at other positions for a substring equal to output.
This would be more readable as "as long as strs[i] does not start with the prefix, shorten the prefix by 1. An empty prefix (output) would exit the loop. (You might then also break out of the for loop.)

!= 0 means that the prefix string did not start at the beginning of the string. If the index > 0 it was further into the string. If it was -1 it didn't exist in the string at all. If it was == 0 it started at the beginning.
Notice that the while loop keeps backing up using substring until a prefix matches the beginning. Then it exits the while loop. Then it continues to see if the next string contains the first and backs up until they share an equal prefix. This continues until either a longest common prefix is returned or an empty string.

Related

Java write recursive function that accept int : k and print to screen k of "*" [duplicate]

This question already has answers here:
How Do I Print the values in a recursive Program in Java?
(5 answers)
Closed 2 years ago.
java write recursive function that accept int : k and print to screen k of "*"
Attempt:
public static String numStarec(int k) {
String ans = "";
if (k == 0) {
ans += "*";
return ans;
}
return numStarec(k-1);
}
this code not work and print for me only "*" ones I know the problem
I tried to fix that but , unfortunately without successes
Example :
k = 3
console : ***
You can append an asterisk after each recursive call, with the base case returning an empty string when k is 0.
public static String numStarec(int k) {
if(k == 0) return "";
return numStarec(k-1) + "*";
}
Demo
Before writing the solution to the problem, I think it would be valuable for you to understand the definition of recursion and what is it that you want to happen. First things first, "recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem" (Source).
If the previous definition still confuses you a bit then lets take a look at the solution to your problem:
public static String numStarec(int k) {
if (k == 0) {
return "";
}
return numStarec(k-1) + "*";
}
As the definition says, "method of solving a problem..." (In this specific case the problem you have is that you want to print the character * an amount K of times on screen) "...where the solution depends on solutions to smaller instances of the same problem" (Where these smaller instances of the same problem consist on finding out how many characters '*' are left to be printed, which is what the value of K is for)
What is happening when you provide the function numStarec with a certain number K is that it will take K and check whether it is 0 or not. If K == 0 evaluates to true then the return statement will be "" but while K != 0 evaluates to true, what will happen is that the function will return the character "*" and keep on invoking itself with the value of K-1 and once again return accordingly.
Hope it helps you understand a little bit about recursion.

java regex questions [closed]

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
Given that I have a string of number, like "12354789556", I need to check that string whether has digits from 0 to 9 at least once.
Can anyone tell me whether i can express this in regex please?
If your strings contains only digits for example "123548955664789556" then try:
System.out.println(myString.chars().distinct().count() == 10);
if your string can also contain letters for example sth like "bbb1235489556fhjerfs64789556"
System.out.println(myString.replaceAll("[^\\d]", "").chars().distinct().count() == 10);
With lookaheads :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
If you want to restrict the string to digits only in addition to making sure it contains every digit :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)\d+$
Note that a version without lookaheads would be technically possible, but would realistically have to be crafted by code as it would have to enumerate all possible orders between digits (10! = 3628800 enumerations).
You can also do it in Java like this:
boolean containsAll = true;
for (int i = 0; i < 10; i++) {
if (!str.contains("" + i)) {
containsAll = false;
}
}
return containsAll;
A non-regex way would be to loop through the String and return false if the indexOf returns -1:
static boolean checkAll(String s, char[] allNums) {
for (int i = 0; i < allNums.length; i++) {
if (s.indexOf(allNums[i]) == -1) {
return false;
}
}
return true;
}
Example

How can I split a string on parenthesis in java except those which are present inside words [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 6 years ago.
Improve this question
My string for example is :
(My Na(#me is Sameer)
I want the output while splitting on parenthesis as :
(
My
Na(#me
is
Sameer
)
I would start up by splitting it using any space character as a separator (i.e. " \t\r\n").
String challenge = "(My Na(me is Sameer)";
String[] parts = challenge.split("\\s*");
But also multiple consecutive spaces are handled as 1 separator. You don't want to have an empty String (i.e. "") whenever there are 2 consecutive spaces.
Next, I will put everything in a List. First of all, because it is my impression that in reality you don't just want to print this text. You probably want to use them somewhere else in your code, e.g. by passing them as an argument to another method.
There are multiple list types to pick from (e.g. ArrayList). In this case, I need to do one more modification to the content of the list. I'm planning to split elements if they start or end with a bracket ( or ). For this reason I'm using a LinkedList. Because linked lists are more performant to insert elements halfway the list.
List<String> partList = new LinkedList<>(Arrays.asList(parts));
So here we go, let's iterate all elements. If an element starts with a bracket, then split it up in 2 elements. For elements that end with a bracket same thing.
for (int i = 0; i < partList.size(); i++) {
String part = partList.get(i);
if (part.startsWith("(")) {
partList.set(i, part.substring(1));
partList.add(i, "(");
} else if (part.endsWith(")")) {
partList.set(i, part.substring(0, part.length() - 1));
partList.add(i + 1, ")");
i++;
}
}
Now, notice that I'm incrementing the index when I add a ")" element, which is necessary to avoid an endless loop.
And there is some shortcoming in this approach. If you would have a phrase that looks like this: "(((mytext)))" It may not do what you hoped for. But I'm assuming that this is outside the scope of your question. It could be solved by adding more code, but I didn't want to make it too complicated.
Finally I'm printing everything.
for (String part : partList) {
System.out.println(part);
}
EDIT:
For the sake of being complete. The following implementation is slightly more complicated, but also tackles the corner cases.
String challenge = "((this is a) rea(lly go)od (((challenge))))";
String[] parts = challenge.split("\\s");
List<String> partList = new LinkedList<>(Arrays.asList(parts));
for (int i = 0; i < partList.size(); i++) {
String part = partList.get(i);
// avoid eternal loops
if (part.length() == 1) continue;
if (part.startsWith("(")) {
partList.set(i, part.substring(1));
partList.add(i, "(");
// will reprocess, because the part is automatically shifted 1 position in the list.
}
else if (part.endsWith(")")) {
partList.set(i, part.substring(0, part.length() - 1));
partList.add(i+1, ")");
// reprocess this element, there could be more ")" braces.
i--;
}
}
If you are looking some help you should come up with what you have tried so far. In here you can do following things.
split your original String by space.
then you can iterate the resulting substrings and check whether a substring contains parenthesis either start or the end of the substring. If so you can split them again by parenthesis.
This regex will match only the parenthesis you want: \B[)(]\b|\b[)(]\B|\B[)(]\B
Here it is as a Java String:
"\\B[)(]\\b|\\b[)(]\\B|\\B[)(]\\B"
\b matches word boundaries
\B matches non-word boundaries
If parenthesis appears only at the beginning and end of the sentence then split it first with substring and then with spaces.
If the parenthesis can appear anywhere in the middle of the sentence(start or end of the word), then first spilt the based on white space, then iterate through each word and spilt again based on parenthesis at start and end of the word. You can use below code (of course, this can be enhanced further)
String test = "(My Na(me (is) Jack)";
String[] splitWords = test.split(" ");
for (String word : splitWords) {
int size = word.length();
if (word.startsWith("(") && word.endsWith(")")) {
System.out.println("(");
System.out.println(word.substring(1, size - 1));
System.out.println(")");
} else if (word.startsWith("(") && !word.endsWith(")")) {
System.out.println("(");
System.out.println(word.substring(1, size ));
} else if (!word.startsWith("(") && word.endsWith(")")) {
System.out.println(word.substring(0, size - 1));
System.out.println(")");
} else {
System.out.println(word);
}
}
This will produce the output as below.
(
My
Na(me
(
is
)
Jack
)

Scope of Local Variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm still confused with scope of local variable
This code doesn't work because i in "i & n" is not resolved. I have identified it on for loops as int i =0. is it not enough? (This is adding nth character altogether our of string).
public String everyNth(String str, int n) {
String result = "";
for (int i = 0; i <= str.length(); i++); {
if (i%n == 0) {
result = result + str.charAt(i);
}
else {
result = result;
}
}
return result;
}
To expand on Jon Skeet's answer-worthy comment, the semi-colon at the end of for (int i = 0; i <= str.length(); i++); finishes the for-statement, and i is no longer in scope after the semi-colon.
You are a few errors:
You can remove the else{ ... } part because you don't need it.
You have a extra ';' in your for loop statement.
There is a mistake on the index of the for loop. You need to do 'i less than' str.length(), instead of i<=str.length(). Basically your for loop will try to access the full-length index of your character array, but actually it exceeds length. For example, the index for string 'hello' is 0,1,2,3,4. But "hello".length() is actually 5. If you try to access the 5th index of your string, you will see a 'java.lang.StringIndexOutOfBoundsException' exception.
Also, you want the every Nth value, you want to do (i-1)%n. Again it is because of the index issue. Try to plug in parameters in your logic and use your pencil to write down the result, and you will see why.
And of course when i==0, you don't want (0-1)%n to happen. So skip i==0 by adding 'i!=0'.
Now, the following is the working code:
public static String everyNth(String str, int n) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if ((i-1)%n == 0 && i!=0)
result = result + str.charAt(i);
}
return result;
}

Occurrences of a substring in a string without using string functions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to know how to count the occurrences of a particular sub-string in a string without using any of the built in JAVA string functions. For example:
InputString = "knowbutuknow"
subString = "know"
The program should return the result as 2.
EDIT: Re-phrased my question. This is one of those interview questions I came across.
EDIT: Basic string functions like charAt and length can be used here.
Assuming, you already know the keyword you are searching for:
Start at char "0" of Input String
Iterate until "length - keyWordLength" (keyword of length 4 can not match into the last 3 chars)
Inside: Iterate from 0 to keyWord.length -1 and always compare:
Char at Position of outer loop PLUS position of inner loop of the Input string with the char at "inner loops" position of the keyword.
if you find a match, go ahead with the innerloop, if it does not match, advance the outer loop, by simple "breaking" the inner loop.
If you have a match, and completely processed the inner loop, you have a match of that keyword.
Something like this. I'm Assuming String.length to be allowed. Otherwhise you would need to create your own strlen function. (This can be achieved, using a forach loop and simple counting "up")
This is untested and may not work out of the box, but should give you a brief idea.
String inputString = "knowbutuknow";
String subString = "know";
int matches = 0;
for (int outer = 0; outer <= inputString.length() - subString.length(); outer++){
for (int inner = 0; inner < subString.length(); inner++){
if (inputString.charAt(outer + inner) == subString.charAt(inner)){
// letter matched, proceed.
if (inner == subString.length()-1){
//last letter matched, so a word match at position "outer"
matches++;
//proceed with outer. Room for improvement: Skip next n chars beeing
// part of the match already.
break;
}
}else{
//no match for "outer" position, proceed to next char.
break;
}
}
}
edit: Sorry, mixed in some php :) fixed it.

Categories