Input : "107501AB021F"
Output: "1075 1AB 21F"
Assume the input is always of 12 digit hexadecimal value.
For each 2 digit char, if 0 occurs on the first position, it should be replaced with space
I know we can do this with an if condition and a charAt, but is there an option to do this without using it?
I believe the most efficient solution is to iterate and compare every second char in char array.
public class ReplaceOddIndexesInString {
public String replace(final String hex){
final char[] arr = hex.toCharArray();
for (int i = 0; i<arr.length; i=i+2) {
if (arr[i]=='0'){
arr[i]=' ';
}
}
return new String(arr);
}
#Test
public void testIt(){
TestCase.assertEquals("1075 1AB 21F", replace("107501AB021F"));
}
}
Related
I am trying to write a method which returns the number of times the first character of a string appears throughout the string. This is what I have so far,
public int numberOfFirstChar0(String str) {
char ch = str.charAt(0);
if (str.equals("")) {
return 0;
}
if ((str.substring(0, 1).equals(ch))) {
return 1 + numberOfFirstChar0(str.substring(1));
}
return numberOfFirstChar0(str);
}
however, it does not seem to work (does not return the correct result of how many occurrences there are in the string). Is there anything wrong with the code? Any help is appreciated.
This uses 2 functions, one which is recursive. We obtain the character at the first index and the character array from the String once instead of doing it over and over and concatenating the String. We then use recursion to continue going through the indices of the character array.
Why you would do this I have no idea. A simple for-loop would achieve this in a much easier fashion.
private static int numberOfFirstChar0(String str) {
if (str.isEmpty()) {
return 0;
}
char[] characters = str.toCharArray();
char character = characters[0];
return occurrences(characters, character, 0, 0);
}
private static int occurrences(char[] characters, char character, int index, int occurrences) {
if (index >= characters.length - 1) {
return occurrences;
}
if (characters[index] == character) {
occurrences++;
}
return occurrences(characters, character, ++index, occurrences);
}
Java 8 Solution
private static long occurrencesOfFirst(String input) {
if (input.isEmpty()) {
return 0;
}
char characterAtIndexZero = input.charAt(0);
return input.chars()
.filter(character -> character == characterAtIndexZero)
.count();
}
Here is a simple example of what you are looking for.
Code
public static void main(String args[]) {
//the string we will use to count the occurence of the first character
String countMe = "abcaabbbdc";
//the counter used
int charCount=0;
for(int i = 0;i<countMe.length();i++) {
if(countMe.charAt(i)==countMe.charAt(0)) {
//add to counter
charCount++;
}
}
//print results
System.out.println("The character '"+countMe.charAt(0)+"' appears "+ charCount+ " times");
}
Output
The character 'a' appears 3 times
Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}
/* returns the index of the first occurrence of any of the
* characters in chars in String s or -1 if none of the characters
* in chars are found in s. */
Above are the instructions, below is my code.
public static void main(String[] args){
indexOfAny("kabomba","bomb");
}
public static int indexOfAny(String s, String chars) {
int index = 0;
String rev = "";
for(int i = s.length()-1;i>=0;i--){
rev+=s.charAt(i);
}
String x = rev;
for(int i = 0;i<x.length();i++){
for(int j = 0; j<chars.length();j++){
if(x.charAt(i)==chars.charAt(j)){
index = i;//**
}else {
index = -1;
}
}
}
System.out.println(index);
return index;
}
To rephrase, the problem is at ** where the it will reach string x last character and compare if the characters in chars string are same and return -1, but I want the code to end and return the index of string x at the i after the last occurrence of any of characters from string chars in string x.
so the output should be 4. because the index of b, which is one of characters of string chars, in the reverse string is 4, which is what I want.
You can use StringUtils class which prevents to iterate the loop.
Here are the indexOf methods present.
OR
You can use String.indexOf method which is present under string class.
IndexOf is already available as part of std java.
for this question:
Given a non-empty string and an int N, return the string made starting
with char 0, and then every Nth char of the string. So if N is 3, use
char 0, 3, 6, ... and so on. N is 1 or more.
everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg"
I get a "Type mismatch: cannot convert from char to String" when trying the following:
public String everyNth(String str, int n) {
for (int i=0; i<str.length(); i = i +n) {
return str.charAt(i);
}
}
However, if I use this:
public String everyNth(String str, int n) {
String result = "";
// Look at every nth char
for (int i=0; i<str.length(); i = i + n) {
result = result + str.charAt(i);
}
return result;
}
then the results are fine.
Is this error because I was trying to return an int when the question is originally in String?
How can I avoid this in the future?
Any tips?
Thanks in advance.
A char and a String are different types. Your second solution is correct. It is defined as String and it returns a String. Your first solution is wrong in two ways: it returns a char when a String is expected, and it puts a return statement in a for loop. You can only return once from a function, so the for loop is useless in that function.
Yes, this is a type mismatch
public String everyNth(String str, int n) {
says that your method returns type String, but
return str.charAt(i);
is actually returning a character.
you can change that line to
return Character.toString(str.charAt(i));
or
return String.valueOf(str.charAt(i));
str.charAt(i) returns a char. This is not the same as a String, which is why the compiler complains about type mismatch.
You could use String.valueOf(theChar) to convert it.
Or you could use str.substring(i, i+1) to get a String (with just a single character) instead of a char.
This loop:
for (int i=0; i<str.length(); i = i +n) {
return str.charAt(i);
}
returns the first char of the string, because the loop terminates (due to the return) on the first iteration, but the method is declared to return String (not char).
Incidentally, you can solve the whole task in one line:
public String everyNth(String str, int n) {
return str.replaceAll("(?:.{" + --n + "}(.))|.*", "$1");
}
I was trying out this question :
Write a function using Recursion to display all anagrams of a string entered by the user, in such a way that all its vowels are located at the end of every anagram. (E.g.: Recursion => Rcrsneuio, cRsnroieu, etc.) Optimize it.
From this site :
http://erwnerve.tripod.com/prog/recursion/magic.htm
This is what i have done :
public static void permute(char[] pre,char[] suff) {
if (isEmpty(suff)) {
//result is a set of string. toString() method will return String representation of the array.
result.add(toString(moveVowelstoEnd(pre)));
return;
}
int sufflen = getLength(suff); //gets the length of the array
for(int i =0;i<sufflen;i++) {
char[] tempPre = pre.clone();
char[] tempSuf = suff.clone();
int nextindex = getNextIndex(pre); //find the next empty spot in the prefix array
tempPre[nextindex] = tempSuf[i];
tempSuf = removeElement(i,tempSuf); //removes the element at i and shifts array to the left
permute(tempPre,tempSuf);
}
}
public static char[] moveVowelstoEnd(char[] input) {
int c = 0;
for(int i =0;i<input.length;i++) {
if(c>=input.length)
break;
char ch = input[i];
if (vowels.contains(ch+"")) {
c++;
int j = i;
for(;j<input.length-1;j++)
input[j] = input[j+1];
input[j]=ch;
i--;
}
}
return input;
}
Last part of the question is 'Optimize it'. I am not sure how to optimize this. can any one help?
Group all the vowels into v
Group all consonants into w
For every pair of anagrams, concat the results