Code Interview(2)——String

Code Interview—— Arrays and Strings

Tips:

1, The use of StringBuffer

StringBuffer can reduce the complexity in concatenating strings.

String[] strs={"abc","def","xyz"};
StringBuffer sf=new StringBuffer();
for(String s:strs){
    sf.append(s);
}
return sf.toString();//concat all the String into a long String. 

It is better than

String[] strs={"abc","def","xyz"};
String newstr="";
for(String s:strs){
    newstr=newstr+s;
}
return newstr;

2, equals()

The equals() method in java.util.String is overwritten that a.equals(b) will return “true” if a and b have the same content. We can call it value-equal.

‘equals()’ method in other java.long.Object is to tell whether two objects store in the same address in memory.

‘==’ for all Object class including String is to tell whether two objects store in the same location. We call it location-equal.

java中equals方法的用法以及==的用法

I have make mistakes in this point, be careful.

3, Handle pointers carefully

In many questions about Strings and Arrays., we use pointer to locate the elements in them. Sometimes, we use more than one pointer. I have made dozens of mistakes in counting the pointer correctly. Always we need to test our code several times to make them completely right.

4, Write pseudo code

Writing pseudo code seems a waste of time. However, the truth is it save time. Pseudo code can make the logic clear and avoid careless mistakes. What’s more, pseudo code can be written in your own words so that it is easy to memorize.

Pseudo Code and Complete Solution for Some Questions:

Q1

Given two Strings, write a method to decide if one is a permutation of the other

之前我理解错了题意,我把permutation(排列)当成了reverse(倒序),因此写了下面的代码,但依然有意义
PC:

1,compare the lengths of 2 Strings, if != return false; if==,next;
2,define a index point to the first string from head to tail, and calculate another index point to the second string from tail to head;
3, build a “for“ or “while” circle to traverse the string. compare the two char according to the two indexes. if value-equals, continue, if not ,break, return false;
4,if the circle finish successfully, return true;

Solution:

    boolean isReverse(String str1,String str2){

        if(str1.length()!=str2.length()){
            return false;
        }

        int index=0;
        int len=str1.length();
        while(index<len-1){
            if(str1.charAt(index)!=str2.charAt(len-1-index)){
                return false;
            }
            index++;
        }
        return true;
    }

关于是否是同排列的算法如下:

String sort(Strings s){
    char[] content=s.toCharArray();
    java.util.Arrays.sort(content);
    return new String(content);
}
boolean isPemutation(String str1,String str2){
    if(str1.length()!=str2.length()){
        return false;
    }
    return sort(str1).equals(sort(str2));
}

几个知识点:
1,先排除字符串长度不对的情况,然后对于排列不同的字符串,排序之后的字符串一定相同;
2,字符串与字符数组的转换:

//字符串转字符数组
Char[] charArray=string.toCharArray();
//字符数组转字符串
String newstring=new String(charArray);

3,JDK自带的排序算法
java.util.Arrays.sort

Q2

Write a method to replace all spaces in a string with “%20” ,you may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the “true” length of the string.
Input: “Mr John Smith ”
Output:”Mr%20John%20Smith”

PC I am not sure whether it is a optimized algorithm, but i works.

1, Define a StringBuffer to produce the new string (newstr)
2, Two pointer current and previous. “current” store the current char in the input string, “previous” remember the previous char.
3, Traverse the input string and move the two pointer. 4 Status is possible: 1)”%20” will be appended into the new string when previous is a “space” and current is not. 2)when previous and current are both not “space”, append the current char to newstr 3) if current is a space no matter what previous is, do nothing;
4, After the former case , move the pointer previous = current
5, Finally, return sb.toString()

I can imagine this question can be solved using a char string. I will add it if necessary.

Solution:

    String replaceSpaces(String str){
        int len=str.length();
        boolean previous=false;
        boolean current=false;
        StringBuffer sf=new StringBuffer();
        for(int i=0;i<len;i++){
            String s=str.substring(i, i+1);
            if(s.equals(" ")){
                current=true;
            }else{
                current=false;
                if(previous==true){
                    sf.append("%20").append(s);
                }else if(previous==false){
                    sf.append(s);
                }
            }
            previous=current;
        }
        return sf.toString();
    }

书后的解答和题干给的例子矛盾:书后的算法是对于字符串尾的空格也转化为%20;算法截然不同。

    String replaceSpaces(String str){
        int len=str.length();
        int spaceCount=0;
        for(int i=0;i<len;i++){
            if(str.charAt(i)==' '){
                spaceCount++;
            }
        }
        int newlength=len+spaceCount*2;
        char[] charArray=new char[newlength];
        for(int j=len-1;j>0;j--){
            if(str.charAt(j)==' '){
                charArray[newlength--]='0';
                charArray[newlength--]='2';
                charArray[newlength--]='%';
            }else{
                charArray[newlength--]=str.charAt(j);
            }
        }

        return new String(charArray);
    }

知道了字符数组和字符串的转换方式,就可以使用以上的方式来代替StringBuffer。字符串的操作显然更灵活。

Q3:

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabbcccccddd would become a2b2c5d3. If the “compressed” string is not smaller than the original string, return the original string.

PC

1, Define StringBuffer sb, String newstr, two pointer previous and current , int count =1
2, previous =the first char; current = the second
3, Traverse the String from the second char;
if current and previous value-equals: count++;else: sb.append(previous);sb.append(count);
previous=current;
4, handle the last one or several charaters:
sb.append(previous);sb.append(count);
newstr=sb.toString()
5, compare the length of the new string and the original one. If new is shorter than original, return newstr; if not, return original;

Solution:

public static String stringCompression(String str){

        if(str==null){
            return null;
        }
        int count =1;
        int len=str.length();
        StringBuffer sb=new StringBuffer();
        String previous=str.substring(0,1);
        String current=null;
        for(int i=1;i<len;i++){
            current=str.substring(i,i+1);
            if(current.equals(previous)){
                count++;
            }else{
                sb.append(previous);
                sb.append(Integer.toString(count));
                count=1;
            }
            previous=current;
        }
        sb.append(previous);
        sb.append(Integer.toString(count));

        String newstr=sb.toString();
        if(newstr.length()<str.length()){
            return newstr;
        }
        return str;

    }

Q4

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees, Can you do it in place?

Without considering the space consume,it is very easy.
I implement clockwise/anticlockwise rotate and horizontal/vertical flip below.

Solution:

public class MatrixTransform {

    //rotate clockwise
    public static int[][] rotateACW(int[][] matrix){
        int m=matrix.length;
        int n=matrix[0].length;

        int[][] newmat=new int[n][m];

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                newmat[n-1-j][i]=matrix[i][j];
            }
        }
        return newmat;

    }

    //rotate anticlockwise
    public static int[][] rotateCW(int[][] matrix){
        int m=matrix.length;
        int n=matrix[0].length;

        int[][] newmat=new int[n][m];

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                newmat[j][m-1-i]=matrix[i][j];
            }
        }
        return newmat;

    }

    //flip vertical
    public static int[][] flipV(int[][] mat){
        int m=mat.length;
        int n=mat[0].length;

        int[][] newmat=new int[m][n];

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                newmat[m-1-i][j]=mat[i][j];
            }
        }
        return newmat;
    }

    //flip horizontal
    public static int[][] flipH(int[][] mat){
        int m=mat.length;
        int n=mat[0].length;

        int[][] newmat=new int[m][n];

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                newmat[i][n-1-j]=mat[i][j];
            }
        }
        return newmat;
    }


    public static void main(String[] args) {

        int[][] matrix={{1,2,3},{4,5,6}};

        System.out.println("逆时针旋转");
        int[][] newmat1=rotateACW(matrix);

        for(int i=0;i<newmat1.length;i++){
            for(int j=0;j<newmat1[0].length;j++){
                System.out.print(newmat1[i][j]+" ");
            }
            System.out.println();
        }

        System.out.println("顺时针旋转");
        int[][] newmat2=rotateCW(matrix);

        for(int i=0;i<newmat2.length;i++){
            for(int j=0;j<newmat2[0].length;j++){
                System.out.print(newmat2[i][j]+" ");
            }
            System.out.println();
        }

        System.out.println("水平翻转");
        int[][] newmat3=flipH(matrix);

        for(int i=0;i<newmat3.length;i++){
            for(int j=0;j<newmat3[0].length;j++){
                System.out.print(newmat3[i][j]+" ");
            }
            System.out.println();
        }

        System.out.println("垂直翻转");
        int[][] newmat4=flipV(matrix);

        for(int i=0;i<newmat4.length;i++){
            for(int j=0;j<newmat4[0].length;j++){
                System.out.print(newmat4[i][j]+" ");
            }
            System.out.println();
        }
    }

}

Q5:

Assume you have a method isSubstring shich checks if one word is a substring of another. Given two strings, s1 and s2, writer code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g. “waterbollte” is a rotation of “erbolltewat”).
rotation:回环

Solution:very tricky

return isSubstring(s1+s1,s2);

Q6

Implement an algorithm to determine if a String has all unique characters. What if you cannot use additional data structures?

    public boolean isUniqueChars(String str){
        if(str.length()>256){
            return false;
        }
        boolean[] hasChar=new boolean[256];
        for(int i=0;i<str.length();i++){
            int val=str.charAt(i);
            if(hasChar[val]==true){
                return false;
            }else{
                hasChar[val]=true;
            }
        }
        return true;
    }

Before coding, you should first ask what is the String exactly like? ASCII or Unicode or just 0~9,a~z.

boolean isUniqueChars(String str){
    int checker=0;
    for(int i=0;i<str.length();i++){
        int val=str.charAt(i)-'a';
        if((checker&(1<<val))>0){
            return false;
        }
        checker|=(1<<val);
    }
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值