Algorithm:Find first non-repeated character in an input string [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have seen this and this question but mine is different. I want to write an efficient code for it in java. I came up with 2 solutions:
Approach 1.
find_first_reapeted(char[] input)
{
HashMap<Character,Integer> myhash = new HashMap<Character,Integer> ();
for(int i=0;i<input.length;i++)
{
if(myhash.containsKey(input[i])
myhash.put(input[i],2); //just put 2 even if it is more than 2
else
myhash.put(input[i],1);
}
for(int i=0;i<input.length;i++)
{
if(myhash.getValue(input[i])==1)
return input[i];
}
}
Approach 2.
find_first_reapeted(char[] input)
{
int[] allchars = new int[26];
for(int i=0;i<input.length;i++)
{
allchars[input[i]-'a'] += 1;
}
for(int i=0;i<input.length;i++)
{
if(allchars[input[i]-'a']==1)
return input[i];
}
}
First is there any better solution? (int term of time and space complexity)?
If not which one of the the above is better? I'm not sure about the space complexity of hashmap!

How about
The first repeating character.
char find_first_repeated(char[] input) {
BitSet bs = new BitSet();
for(char c : input) {
if(bs.get(c))
return c;
bs.set(c);
}
return '\uffff'; // invalid char
}
The first non repeating character, I would use the second approach but using the for-each loop to make it cleaner.

Related

I would like to swap every second character of a string [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 2 years ago.
Improve this question
I would like to swap every second character of a string like so:
welcome -> ewclmoe
How can I do this?
I would prefer to build the output with a StringBuilder. Iterate the even indices of the original String. First append the next odd character (if there is one), then take the even character. Like,
String s = "welcome";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
if (i + 1 < s.length()) {
sb.append(s.charAt(i + 1));
}
sb.append(s.charAt(i));
}
System.out.println(sb);
Outputs (as requested)
ewclmoe
below code works...
check it out...
public static void swapCharacter(String s) {
char[] a = s.toCharArray();
char temp;
for(int i=0; i<a.length-1;i+=2)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
System.out.println(new String(a));
}
public static void main(String[] args) {
swapCharacter("welcome");
}

How to convert every other character to upper case in a string [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 5 years ago.
Improve this question
I currently have an assignment where we have the entire (swedish) alphabet in lower case as a string, and we should convert every other character to upper case. This is where I am right now:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
for (int i = 0; i < 29; i = i + 2) {
char result = alphabet.charAt(i);
alphabet.toUpperCase(result);
}
System.out.println(alphabet);
}
The problem now is that alphabet.toUpperCase(result); gives me an error that I can't convert char to locale. How do I fix this?
If you want to get the uppercase of a char, you should use Character.toUpperCase(c), not String's toUpperCase.
So, I think you might be looking for something like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < alphabet.length(); i++) {
char c = alphabet.charAt(i);
sb.append(i % 2 == 0 ? Character.toUpperCase(c) : c);
}
String result = sb.toString();
System.out.println(result);
}
Output:
abcdefghijklmnopqrstuvwxyzåäö
AbCdEfGhIjKlMnOpQrStUvWxYzÅäÖ
Since Strings are immutable, you have to create a new String to get what you want. An efficient way of doing this is with a StringBuilder.
Edit:
Another way to do it without StringBuilder and perhaps a more intuitive way is to convert the String to an array of chars, which makes it mutable. In the end, you just convert it back to a String. The result would look like this:
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
System.out.println(alphabet);
char[] chars = alphabet.toCharArray();
for (int i = 0; i < alphabet.length(); i+=2) {
chars[i] = Character.toUpperCase(chars[i]);
}
String result = new String(chars);
System.out.println(result);
}

Split Strings, Search and Translate Substrings JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm pretty new to Java, and I need to solve this problem for an assignment. Can anyone help me please?
The problem is we need to enter a String like "AUGUUUUCU" and then split it into three letter strings like "AUG", "UUU", "UCU".
After that I would have to iterate over these and translate them to "AUG = METIONINA", "UUU = FENILANINA", "UCU = SERINA". Can anyone help me with this?
I already found a way to split them:
public class Main {
public static void main(String[] args) {
String str = "AUG-UUU-UCU";
String delimiter = "-";
String[] temp;
temp = str.split(delimiter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}
If you're supposed to take user input, then you'll need to use a Scanner:
Scanner sc = new Scanner(System.in);
String input = sc.next();
To split it into three-letter Strings, use an array and store the substrings in the array using a for loop:
String[] subs = new String[input.length()/3];
int index;
for (int i=0; i<input.length(); i++) {
index = i*3;
subs[i] = input.substring(index, index+3);
}
You could then iterate over the array with another for loop and use a switch statement to determine the correct output:
for (int i=0; i<subs.length; i++) {
switch(subs[i]) {
case "AUG":
System.out.println("METIONINA");
break;
case "UUU":
System.out.println("FENILANINA");
break;
case "UCU":
System.out.println("SERINA");
break;
default:
break;
}
}
Note the break statements within the switch block. These are important to include; without break statements, it will simply execute all code after the matching case.
You could create an array that holds the values that are to be translated.
translateArray = new String[3];
Then you could set the values of the parallel array based on the input you receive. Then you could post those values.
for (int i=0; i<temp.length ; i++) {
if (temp[i] == "AUG" ) {
translateArray[i] = "METIONINA";
}
if (temp[i] == "UUU") {
translateArray[i] = "FENILANINA";
}
if (temp[i] == "UCU") {
translateArray[i] = "SERINA";
}
System.out.println(temp[i] + " = " + translateArray[i]);
}
Maybe that will work better for you.
To split a string into strings 3 chars long is 1 line:
String[] words = str.split("(?<=\\G...)");

How to reverse word leaving all instance of q in place [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How do I write a method that will reverse the letters of each word in a string while leaving all instances of ‘Q’ or ‘q’ in place (stay at the current index). Each word is separated by whitespace(‘ ‘).
Examples:
Hello Worldq > olleH dlroWq
Hiq BQb -> iHq bQB
kjnoqKl -> lKonqjk
jkQuq -> ukQjq
public String reverseWords(String s) {
String[] sub = s.trim.split(“q + ”);
String result = ””;
if (sub.length > 0) {
for (int i = sub.length - 1; i > 0; i--) {
result += sub[i] + ““;
}
}
return result;
}
Here is my solution. What I did first was parse the initial String so we can get individual words. From there, I replaced all the Q and q for that word with an empty string and then reversed it using StringBuilder. Well with StringBuilder you can also insert pretty easily, so I looped back through the word and added all the Q and q back to the orginial spot.
public static void main(String... array){
System.out.println(reverseWords("Hello Worldq"));
}
public static String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder output = new StringBuilder(words.length);
for (String word : words){ //Iterate through words
StringBuilder temp = new StringBuilder(word.replaceAll("[Qq]", "")).reverse(); //Replace Q's and reverse
for (int i =0; i<word.length(); i++){ //find Q's
char tempChar = s.charAt(i);
if (tempChar == 'Q'){ //If q found insert
temp.insert(i, "Q");
}
if (tempChar == 'q'){
temp.insert(i, "q");
}
}
output.append(temp); //Add to final output
output.append(" "); //Do not forget about space
}
return output.toString();
}
Hope this helps!
Edit:
Some after thoughts, you could potentially store the indexes of the Q's when iterating through the word initially when trying to replaceAll. That way you replaceAll and have the indexes of all the Q's with one iteration instead of 2.
I would do it in two step. First of all, construct a list, or array containing all letters that are not Q or q. Reverse the array.
Then you reconstruct the array by replacing all the non q letters with the reveresed array like this:
int reversedIndex = 0;
for(int i=0; i<s.length(); i++){
if (s.charAt(i) != 'q' && s.charAt(i) != 'Q') {
s[i] = reversedArray[reversedIndex];
reversedIndex++;
}
}
I leave you to make the code to program the reversedArray
Why not just implement a spare string/array with the q or Q included, reverse the string/array to the place -1 space for the q or Q, and if you come across one in your word/place in the array just do nothing be an if statement in your reverse method.Then put that in an string/array. Take the next part of the string/array and do the same until your original word is empty, return the final string/array, whatever you want to use, and done

Error reversing a string in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to reverse a String, I know there are thousands of examples, but I wanted to do the job by myself and I created this, but it doesn't work properly.
public String ReverseString(String str){
str = str.toLowerCase();
char normalArr[] = str.toCharArray();
char reversedArr[] = new char[str.length()];
for (int i=str.length()-1; i<=0; i--){
int count = 0;
reversedArr[count] = normalArr[i];
count++;
}
String retValue = new String(reversedArr);
return retValue;
}
In addition to #zaskes answer, you want int count = 0; before the loop, not inside.
Look at the condition of your loop - it should be i >= 0
In addition - your solution allocates an unnecessary array (there are algorithms that perform this with a single array, not yours , though) - I think you should strive to code your programs to be with good performance.
Here's an implementation that does the reverse logic:
StringBuffer reversed = new StringBuffer(str.length());
int loc = str.length();
while (loc > 0) {
char c1 = str.charAt(--loc);
if (Character.isLowSurrogate(c1)) {
assert loc >= 0;
char c2 = str.charAt(--loc);
reversed.append(c2);
}
reversed.append(c1);
}
return reversed.toString();
If you consider the use of StringBuffer for simple appends cheating, you can replace that with:
char[] reversed = new char[str.length()];
int next = 0;
...
reversed[next++] = c1; // instead of .append(c1)

Categories