刷题
1、返回字符串中的元音字母,元音字母为a、e、i、o、u,输入参数只包含小写字母 空格 和“/”(斜杠)
public class Vowels {
public static int getCount(String str) {
int vowelsCount = 0;
// your code here
char []key =str.toCharArray();
for (int i=0;i
if (key[i]=='a' | key[i]=='e' | key[i]=='i' |key[i]=='o' |key[i]=='u'){
vowelsCount++;
}
}
return vowelsCount;
}
}
2、
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
想的思路是将字符串合并为一个,然后依次判断加入到一个新的列表中,然后得到没有重复字符的列表,对其排序转换输出即可。代码如下
package com.csu;
import java.util.TreeSet;
public class TwoToOne {
public static String longest (String s1, String s2) {
// your code
s1 = s1+s2;
char[] chars = s1.toCharArray();
TreeSet set = new TreeSet<>();
for(char i : chars)
set.add(i);
s1 = "";
for(char i : set)
s1 += i;
return s1;
}
}
3、
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types
public class Kata {
public static int findShort(String s) {
String [] z= s.split(" ") ;
int size =z[0].length();
for (int i=1;i
if (z[i].length()
size=z[i].length();
}
}
return size;
}
}
4、
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.
问题描述:就是将给定字符串变为:第一个单词不变。之后的每个单词的首字母大写。类似于驼峰命名
class Solution{
static String toCamelCase(String s){
String [] aa;
String bb;
String cc="";
if (s.contains("-")) {
aa=s.split("-");
cc=aa[0];
for (int i=1;i
bb=aa[i].substring(0,1).toUpperCase()+aa[i].substring(1);
cc=cc+bb;
}
}
if (s.contains("_")) {
aa=s.split("_");
cc=aa[0];
for (int i=1;i
bb=aa[i].substring(0,1).toUpperCase()+aa[i].substring(1);
cc=cc+bb;
}
}
return cc;
}
}
5、
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
这题的意思是从一堆奇数里挑偶数,一堆偶数里挑奇数,还算简单
public class FindOutlier{
static int find(int[] integers){
int evencount=0,oddcount=0;
int evennum=0,oddnum=0;
for (int i:integers) {
if (Math.abs(i)%2==0) {
evennum=i;
evencount++;
}else {
oddnum=i;
oddcount++;
}
if (evencount>0 && oddcount>0) {
if (evencount>1) {
return oddnum;
}
else if (oddcount>1) {
return evennum;
}
}
}
return evencount>1 ? oddnum:evennum;
}
}
6、
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
DnaStrand.makeComplement("ATTGC") // return "TAACG"
DnaStrand.makeComplement("GTAT") // return "CATA"
public class DnaStrand {
public static String makeComplement(String dna) {
//Your code
char[] chars=dna.toCharArray();
for (int i=0;i
chars[i]=getComplement(chars[i]);
}
return new String(chars);
}
private static char getComplement(char c){
switch(c){
case 'A':return 'T';
case 'T':return 'A';
case 'C':return 'G';
case 'G':return 'C';
}
return c;
}
}
7、
This time no story, no theory. The examples below show you how to write function accum:
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
public class Accumul {
public static String accum(String s) {
// your code
s=s.toLowerCase();
StringBuffer sb=new StringBuffer();
for (int i=0;i
char ch=s.charAt(i);
sb.append(Character.toUpperCase(ch));
for (int j=0;j
sb.append(ch);
}
sb.append("-");
}
return sb.deleteCharAt(sb.lastIndexOf("-")).toString();
}
}
8、
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
public class JadenCase {
public static String toJadenCase(String phrase) {
// TODO put your code below this comment
if(phrase==null || "" .equals(phrase)) {
return null;
}
String[] str=phrase.split(" ");
for (int i=0;i
char [] array=str[i].toCharArray();
array[0]=String.valueOf(array[0]).toUpperCase().charAt(0);
str[i]=String.valueOf(array);
}
StringBuffer sb=new StringBuffer();
for (String i:str) {
sb.append(i+" ");
}
return sb.substring(0, sb.toString().length()-1).toString();
}
}
9、
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
package kata
func DigitalRoot(n int) (total int) {
for n >= 10 {
total += n % 10
n = n / 10
}
total += n
if total >= 10 {
total = DigitalRoot(total)
}
return
}
10、
isIsogram "Dermatoglyphics" == true
isIsogram "aba" == false
isIsogram "moOse" == false -- ignore letter case
找出字符串中的重复字母,不区分大小写。
import java.util.HashSet;
import java.util.Set;
public class isogram {
public static boolean isIsogram(String str) {
Set letter =new HashSet();
for(int i=0;i
if (letter.contains(str.toLowerCase().charAt(i))) {
return false;
}
letter.add(str.charAt(i));
}
return true;
}
}
11、
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
public class XO {
public static boolean getXO (String str) {
// Good Luck!!
int j=0,k=0;
char[]arr1=new char[str.length()];
char[]arr2=new char[str.length()];
char[] ch=str.toLowerCase().toCharArray();
for (int i=0;i
if (ch[i]=='o'){
arr2[j]=ch[i];
j++;
}
else if (ch[i]=='x') {
arr2[k]=ch[i];
k++;
}
}
if (k==j) {
return true;
}
return false;
}
}
12、
The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number.
In effect: 89 = 8^1 + 9^2
The next number in having this property is 135.
See this property again: 135 = 1^1 + 3^2 + 5^3
We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.
Let's see some cases:
sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
If there are no numbers of this kind in the range [a, b] the function should output an empty list.
sum_dig_pow(90, 100) == []
import java.util.ArrayList;
import java.util.List;
public class SumDigPower {
public static List sumDigPow(long a, long b) {
// your code
final List ret=new ArrayList<>() ;
for (long k=a;k<=b;k++) {
long v=0;
int exe=1;
for (char c:(""+k).toCharArray()) {
v+=Math.pow(c-'0', exe);
exe++;
if (v>k) {
break;
}
}
if (v==k) {
ret.add(k);
}
}
return ret;
}
16、
reverses each word in the string.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
public class Kata{
public static String reverseWords(final String original){
// Have at it
String [] array=original.split(" ");
if (array.length==0) {
return original;
}
int i=0;
for (String str :array) {
array[i]=new StringBuffer(str).reverse().toString();
i++;
}
return String.join(" ", array);
}
}
17、
You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.
Example:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
n being the length of the string array, if n = 0 or k > n or k <= 0 return "".
题目意思就是找 k 个字符串加起来的总字符串最长的那个,然后返回这个
class LongestConsec {
public static String longestConsec(String[] strarr, int k) {
if (strarr.length == 0 || k > strarr.length || k <= 0)
return "";
String longestStr = "";
for (int index = 0; index < strarr.length - k + 1; index++) {
StringBuilder sb = new StringBuilder();
for (int i = index; i < index + k; i++) {
sb.append(strarr[i]);
}
if (sb.toString().length() > longestStr.length()) {
longestStr = sb.toString();
}
}
return longestStr;
}
}
18、
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3
题目大意:给出一个长度为奇数且大于3的数组,找出其中不同的那一个数字。
解题思路:直接进行数组的排序,再进行比较,第一个元素跟第二个元素如果相等就直接返回最后一个元素,否则就是第一个元素,因为数组的元素已经排好序了,不同的那一个数要么是最大的,要么是最小的。
import java.util.Arrays;
public class Solution {
static int stray(int[] numbers) {
Arrays.sort(numbers);
return numbers[0]==numbers[1]?numbers[numbers.length-1]:numbers[0];
}
}
19、
Examples
Maskify.Maskify("4556364607935616"); // should return "############5616"
Maskify.Maskify("64607935616"); // should return "#######5616"
Maskify.Maskify("1"); // should return "1"
Maskify.Maskify(""); // should return ""
// "What was the name of your first pet?"
Maskify.Maskify("Skippy"); // should return "##ippy"
Maskify.Maskify("Nananananananananananananananana Batman!"); // should return "####################################man!"
大意:写一个遮罩函数,把除了末尾4个字符之外的其他都改成“#
public class Maskify {
public static String maskify(String str) {
if (str.length()<=4) {
return str;
}
String result="";
for (int i=0;i
result+="#";
}
return result+str.substring(str.length()-4);
}
22
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
import java.util.Arrays;
public class Kata {
public static String HighAndLow(String numbers) {
numbers=numbers.replaceAll(" ",",");
String[] a=numbers.split(",");
int[] arr=new int[a.length];
for(int i=0;i
arr[i]=Integer.parseInt(a[i]);
}
Arrays.sort(arr);
numbers=arr[arr.length-1]+" "+arr[0];
return numbers;
}
30
Sort binary tree by levels
You are given a binary tree:
public class Node {
public Node left;
public Node right;
public int value;
public Node(Node l, Node r, int v) {
left = l;
right = r;
value = v;
}
}
Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.
Return empty list is root is 'null'.
Example 1 - following tree:
2
8 9
1 3 4 5
Should return following list:
[2,8,9,1,3,4,5]
Example 2 - following tree:
1
8 4
3 5
7
Should return following list:
[1,8,4,3,5,7]
pollFirst()删除第一个元素,并返回删除元素的值,如果元素为null,将返回null
public class Kata {
public static List treeByLevels(Node node) {
List out =new ArrayList<>();
ArrayDeque q=new ArrayDeque();
if (node!=null) {
q.add(node);
}
while(!q.isEmpty()) {
node=q.pollFirst();
out.add(node.value);
if (node.left!=null) {
q.add(node.left);
}
if (node.right!=null) {
q.add(node.right);
}
}
return out;
}
}
35
In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120
注意是数据溢出问题
import java.math.BigInteger;
public class Kata{
public static String Factorial(int n) {
BigInteger sum=new BigInteger("1");
BigInteger flat=new BigInteger("1");
if(n<0){
return "-1";//传入的数据不合法
}
if(n==0){
return "1";
}
for (int i=1;i<=n;i++) {
flat=flat.multiply(sum);
sum=sum.add(new BigInteger("1"));
}
return ""+flat;
}
}
40
Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let's consider the following problem. Imagine that you have a pyramid built of numbers, like this one here:
/3/
\7\ 4
2 \4\ 6
8 5 \9\ 3
slide down' is 3 + 7 + 4 + 9 = 23
这里我简单解释一下动态规划方法,从底部开始,把倒数第二层每个元素,分别加上下一层的相邻元素(可以选的下一步),,把最大的一个(最优的下一步)作为这层(倒数第二层)的新元素。
比如:
3
7 4
2 4 6
8 5 9 3
最底下的一层是8 5 9 3,倒数第二层是2 4 6
2可以选择下一层的8或者5作为下一步,而2+8>2+5,故把2+8=10,取代2,
4可以选择下一层的5和9作为下一步,而4+9>4+5,故把4+9=13,取代4的位置
同理6+9>6+3,倒数第二层变成了10 13 15,去掉(无视)最后一层,把倒数第二层最为新的最后一层。
金字塔变成
3
7 4
10 13 15
然后,金字塔变成
3
20 19
到最后只剩下一层,就是23,这个就是最优解了
public class LongestSlideDown {
public static int longestSlideDown(int[][] pyramid) {
for (int r = pyramid.length - 1; r > 0; r--)
for (int c = 0; c < pyramid[r].length - 1; c++)
pyramid[r - 1][c] += Math.max(pyramid[r][c], pyramid[r][c + 1]);
return pyramid[0][0];
}
}
45
"one" => 1
"twenty" => 20
"two hundred forty-six" => 246
"seven hundred eighty-three thousand nine hundred and nineteen" => 783919
import java.util.HashMap;
import java.util.Map;
public class Parser {
public static int parseInt(String numStr) {
String[] numArray = numStr.split("[ |-]");
int number = 0;
Map map = new HashMap();
map.put("zero", 0);
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
map.put("four", 4);
map.put("five", 5);
map.put("six", 6);
map.put("seven", 7);
map.put("eight", 8);
map.put("nine", 9);
map.put("ten", 10);
map.put("eleven", 11);
map.put("twelve", 12);
map.put("thirteen", 13);
map.put("fourteen", 14);
map.put("fifteen", 15);
map.put("sixteen", 16);
map.put("seventeen", 17);
map.put("eighteen", 18);
map.put("nineteen", 19);
map.put("twenty", 20);
map.put("thirty", 30);
map.put("forty", 40);
map.put("fifty", 50);
map.put("sixty", 60);
map.put("seventy", 70);
map.put("eighty", 80);
map.put("ninety", 90);
map.put("hundred", 100);
map.put("thousand", 1000);
map.put("million", 1000000);
for (int i = 0; i < numArray.length; i++) {
for (String key : map.keySet()) {
if (numArray[i].toLowerCase().equals(key)) {
if (map.get(key) == 100) {
int temp = number % 100;
number -= temp;
number += temp * (map.get(key));
}
else if (map.get(key) > 100)
num