LintCode String, Function & Class 第一部分
今天花了点时间刷了LintCode第三单元第一部分的题目,都比较简单。下面一一过下。
第一题: 矩阵面积
实现一个矩阵类Rectangle,包含如下的一些成员变量与函数:
两个共有的成员变量 width 和 height 分别代表宽度和高度。
一个构造函数,接受2个参数 width 和 height 来设定矩阵的宽度和高度。
一个成员函数 getArea,返回这个矩阵的面积。
样例
Rectangle rec = new Rectangle(3, 4);
rec.getArea(); // should get 12
这题是一道基本的构建一个类的题目。代码如下:
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height){
this.width = width;
this.height = height;
}
public int getArea(){
return width*height;
}
}
第二题:动态数组 ArrayList
用 ArrayList 实现一些操作:
create(n). 创建一个大小为n的ArrayList,包含n个整数,依次为[0, 1, 2, … n-1]
clone(list). 克隆一个list。
get(list, index). 查询list中index这个位置的数。
set(list, index, val). 将list中index这个位置的数改为val。
remove(list, index). 移除list中index这个位置的数。
indexOf(list, val). 在list中查找值为val的数,返回它的index。如果没有返回-1。
这道题的要求就是对于ArrayList的一系列操作。代码如下:
public class ArrayListManager {
public static ArrayList<Integer> create(int n) {
// Write your code here
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;i < n;i++){
list.add(i);
}
return list;
}
public static ArrayList<Integer> clone(ArrayList<Integer> list) {
// Write your code here
ArrayList<Integer> list2 = new ArrayList<Integer>();
for(Integer a : list){
list2.add(a);
}
return list2;
}
public static int get(ArrayList<Integer> list, int k) {
// Write your code here
return list.get(k);
}
public static void set(ArrayList<Integer> list, int k, int val) {
// write your code here
list.set(k, val);
}
public static void remove(ArrayList<Integer> list, int k) {
// write tour code here
list.remove(k);
}
public static int indexOf(ArrayList<Integer> list, int val) {
// Write your code here
if (list == null)
return -1;
return list.indexOf(val);
}
}
第三题:Getter与Setter
实现一个School的类,包含下面的这些属性和方法:
一个string类型的私有成员name.
一个setter方法setName,包含一个参数name.
一个getter方法getName,返回该对象的name。
样例
School school = new School();
school.setName(“MIT”);
school.getName(); // 需要返回 “MIT” 作为结果.
这道题是java封装特性的体现。即不能让外部可以直接修改某个类的成员变量的值,而是提供接口让外部操作。通俗的例子就比如说是手机,我们能操作的就是外部的几个按键。此题代码如下:
public class School {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
第四题: 大小写转换 II
将一个字符串中的小写字母转换为大写字母。忽略其他不是字母的字符。
样例
给出 “abc”, 返回 “ABC”.
给出 “aBc”, 返回 “ABC”.
给出 “abC12”, 返回 “ABC12”.
这道题要求我们将字符串中原来不是大写的字母变成大写字母,其他符号不做变换。那么就需要遍历字符串依次判断是否为小写字母,然后做相应操作。这里我使用了StringBuilder来接收传入的字符串。
public class Solution {
public String lowercaseToUppercase2(String str) {
// Write your code here
StringBuilder sb = new StringBuilder(str);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
}
}
return sb.toString();
}
}