For each symbol in the string if it's the first character occurence, replace it with a '1', else replace it with the amount of times you've already seen it...
But will your code be performant enough?
Examples:
input = "Hello, World!"
result = "1112111121311"
input = "aaaaaaaaaaaa"
result = "123456789101112"
Note: there will be no int domain overflow (character occurences will be less than 2 billion).
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class JomoPipi {
public static String numericals(String s) {
Map<String, AtomicInteger> map = new HashMap<>();
StringBuilder result = new StringBuilder();
for (String element :s.split("")) {
int temp;
if(map.containsKey(element)){
temp=map.get(element).incrementAndGet();
}else{
temp = 1;
map.put(element, new AtomicInteger(1));
}
result.append(temp);
}
return result.toString();
}
}
You wrote all your unit test names in camelCase. But some of your colleagues have troubles reading these long test names. So you make a compromise to switch to underscore separation.
To make these changes fast you wrote a class to translate a camelCase name into an underscore separated name.
Implement the ToUnderscore() method.
Example:
"ThisIsAUnitTest" => "This_Is_A_Unit_Test"
But of course there are always special cases...
You also have some calculation tests. Make sure the results don't get splitted by underscores. So only add an underscore in front of the first number.
Also Some people already used underscore names in their tests. You don't want to change them. But if they are not splitted correct you should adjust them.
Some of your colleagues mark their tests with a leading and trailing underscore. Don't remove this.
And of course you should handle empty strings to avoid unnecessary errors. Just return an empty string then.
You are working for NoVirus Security Solutions and they ask you to make a scanner that scans a file inputted by the user with the function scanFile(File,VirusDB) that takes a File and a VirusDB object and return whether a file is safe or not. Remember: the searches need to be non-Case-Sensitive
Your class also has the function setScanIntensity(int) which changes the scan intensity. This will only receive values 0, 1, 2 or 3. This has been done for you.
The scan intensity determines the arrays from the database that will be used. i.e.:
scanIntensity 0 means off(every file is considered safe)
scanIntensity 1 means that only the array intensity1Signatures will be used
scanIntensity 2 means that the arrays intensity1Signatures and intensity2Signatures will be used
scanIntensity 3 means that all 3 arrays will be used
Outputs
The outputs should be: "Filename is safe" or "Filename is not safe" (Filename is the name of the file that you can get with file.getName() )
File Class
class File{
private String name;
private String data;
public File(String name,String data){
this.name = name;
this.data = data;
}
//used in output
public String getName(){
return this.name;
}
//the String that you need to scan.
public String getData(){
return this.data;
}
}
VirusDB Class
class VirusDB{
private String[] intensity1Signatures;
private String[] intensity2Signatures;
private String[] intensity3Signatures;
public VirusDB(String[] intensity1Signatures,String[] intensity2Signatures,String[] intensity3Signatures){
this.intensity1Signatures = intensity1Signatures;
this.intensity2Signatures = intensity2Signatures;
this.intensity3Signatures = intensity3Signatures;
}
public String[] getSignatures(int arrayNum){
switch (arrayNum){
case 1:return this.intensity1Signatures;
case 2:return this.intensity2Signatures;
case 3:return this.intensity3Signatures;
default:return new String[0];
}
}
}
public class AntiVirus{
private int scanIntensity = 0;
//this method is ready for you.
public void setScanIntensity(int level){
scanIntensity = level;
}
//write this method.
public String scanFile(File file,VirusDB database){
String data = file.getData().toLowerCase();
for(int i = 0; i <= scanIntensity; i ++){
String [] signatures = database.getSignatures(i);
for (String signature : signatures) {
if(data.contains(signature))
return file.getName() + " is not safe";
}
}
return file.getName() + " is safe";
}
}
You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre.
If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is.
An example should clarify:
'taxi' would become 'atix' 'taxis' would become 'atxsi'
function insideOut(x){
var result = [];
for(var item of x.split(" ")){
var len = item.length;
if(len>3){
var middle = Math.floor(len/2);
if(len%2 == 0){
item = item.substring(0,middle).split("").reverse().join("").concat( item.substring(middle,len).split("").reverse("").join(""))
}else{
item = item.substring(0,middle).split("").reverse().join("").concat(item.substring(middle,middle+1)).concat( item.substring(middle+1,len).split("").reverse("").join(""))
}
}
result.push(item);
}
return result.join(" ");
}
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
solution('abc') // should return ['ab', 'c_']
solution('abcdef') // should return ['ab', 'cd', 'ef']
function solution(str){
var result = [];
while(str.length >1){
result.push(str.substring(0,2))
str = str.substring(2,str.length);
}
if(str.length !== 0)
result.push(str+"_")
return result;
}
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
The output expected would be:
apples, pears
grapes
bananas
The code would be called like so:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"
function solution(input, markers){
var comments = input.split('\n');
for (var i in markers) {
for (var j in comments) {
var line = null;
var idx = comments[j].indexOf(markers[i]);
if (idx >= 0) {
comments[j] = comments[j].substring(0, idx).trim();
}
}
}
return comments.join('\n');
}
The cable will be symbolized with a combination of the following characters: -, _, =.
Each character has a different length: - is of length 1, _ of length 2 and = of length 3.
Sometimes the cable is making a loop. This will be symbolized with brackets.
When you have reached a closing bracket ), you have to go back to the corresponding opening bracket and count the length again -> this represents a loop.
If a cable is broken, meaning number of ( is not equal to number of ), you must throw a BracketException of type RuntimeException that you must implement yourself.
If the cable has a node, meaning a different character is detected on the input string, throw a NodeException of type RuntimeException (implement it as well)
If a cable is both broken and contains nodes then it should throw the exception that can be first detected and confirmed.
Good luck and keep an eye on the performance of your code - suboptimal solutions may time out in the Submit tests ;)
동작은 하는데 에러처리등을 직접해줘야 하는데 .. 너무 정보가 부족하다
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.stream.Collectors;
public class Cable {
public static int parse(String x) {
int result = 0;
if (x.equals("-")) {
result = 1;
} else if (x.equals("_")) {
result = 2;
} else {
result = 3;
}
return result;
}
public static BigInteger solve(String cable) throws Exception {
Stack<String> stack = new Stack<>();
String[] cables = cable.split("");
for (String c : cables) {
if (c.equals(")")) {
String temp = null;
List<String> internal = new ArrayList<>();
while (!(temp = stack.pop()).equals("(")) {
internal.add(temp);
}
stack.addAll(internal);
stack.addAll(internal);
} else {
stack.push(c);
}
}
return BigInteger.valueOf(stack.stream().mapToInt(Cable::parse).sum());
}
}
가장 추천을 많이 받은 풀이
import java.util.*;
import java.math.BigInteger;
class BracketException extends RuntimeException {}
class NodeException extends RuntimeException {}
public class Cable {
final private static BigInteger TWO = new BigInteger("2");
public static BigInteger calculateLength(String cable){
BigInteger tot = BigInteger.ZERO;
int lvl = 0,
f = 0;
for (char c: cable.toCharArray()) {
f = 0;
switch (c) {
case '-': f = 1; break;
case '_': f = 2; break;
case '=': f = 3; break;
case '(': lvl += 1; break;
case ')': lvl -= 1; if (lvl<0) throw new BracketException(); break;
default : throw new NodeException();
}
if (f!=0) tot = tot.add( TWO.pow(lvl).multiply( BigInteger.valueOf(f) ));
}
if (lvl!=0) throw new BracketException();
return tot;
}
}
Given a list of languages and your respective test results, return the list of languages where your test score is at least 60, in descending order of the results.
The word i18n is a common abbreviation of internationalization in the developer community, used instead of typing the whole word and trying to spell it correctly. Similarly, a11y is an abbreviation of accessibility.
Write a function that takes a string and turns any and all "words" (see below) within that string of length 4 or greater into an abbreviation, following these rules:
A "word" is a sequence of alphabetical characters. By this definition, any other character like a space or hyphen (eg. "elephant-ride") will split up a series of letters into two words (eg. "elephant" and "ride").
The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "elephant ride" => "e6t r2e").
Example
abbreviate("elephant-rides are really fun!")
// ^^^^^^^^*^^^^^*^^^*^^^^^^*^^^*
// words (^): "elephant" "rides" "are" "really" "fun"
// 123456 123 1 1234 1
// ignore short words: X X
// abbreviate: "e6t" "r3s" "are" "r4y" "fun"
// all non-word characters (*) remain in place
// "-" " " " " " " "!"
=== "e6t-r3s are r4y fun!"
import java.util.regex.*;
public class Abbreviator {
public String abbreviate(String string) {
Pattern p = Pattern.compile("([a-zA-Z]{4,})");
Matcher m = p.matcher(string);
while(m.find())
{
String target = m.group();
String abbr = "" + target.charAt(0) + (target.length()-2) + target.charAt(target.length()-1);
string = string.replaceFirst(target, abbr);
}
return string;
}
}
n this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based except in Fortran where it is 1-based. An opening brace will always have a closing brace. Return -1 if there is no answer (Haskell return Nothing, Fortran: return 0)
For example
solve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10
solve("((1)23(45))(aB)", 1) = 3
solve("((1)23(45))(aB)", 2) = -1 // there is no opening bracket at index 2, so return -1
solve("((1)23(45))(aB)", 6) = 9
solve("((1)23(45))(aB)", 11) = 14
solve("((>)|?(*'))(yZ)", 11) = 14
import java.util.Stack;
public class Indice {
public static int solve(String str, int index){
// write your code
Stack<Integer> stack = new Stack<Integer>();
for(int i =0 ; i < str.length(); i++){
if(str.charAt(i) == '('){
stack.add(i);
}else if(str.charAt(i) == ')'){
if(stack.pop() == index)
return i;
}
}
return -1;
}
}