Domanda di colloquio di Salesforce

How to reverse a String? How to deal with it if the input string is null?

Risposte di colloquio

Anonimo

10 mar 2013

If you want to save on the extra "swap" memory, you can use bitwise operator XOR like this: public String reverse( String string ) { byte[] array = string.getBytes(); for( int i = 0, j = array.length - 1; i < array.length / 2; i++, j-- ) { array[ i ] ^= array[ j ]; array[ j ] ^= array[ i ]; array[ i ] ^= array[ j ]; } return new String( array ); }

2

Anonimo

10 mar 2013

The above approach becomes O(N^2) due to use of += inside a for loop. Every time we use +=, a new string is created from the copied over contents of the last string to which another string is appended. On an average there are N/2 copy operations. This can be bettered using StringBuilder like this: StringBuffer strBuffer = new StringBuffer(); for(int i=a.length()-1; i>=0; i--){ strBuffer.append(a.charAt(a)); } return strBuffer.toString(); } However, this can be improvised even more using the just N/2 iterations (instead of N above) : public String reverse( String string ) { byte[] array = string.getBytes(); byte swap; for( int i = 0, j = array.length - 1; i < array.length / 2; i++, j-- ) { swap = array[ j ]; array[ j ] = array[ i ]; array[ i ] = swap; } return new String( array ); }

1

Anonimo

19 dic 2011

string a=""; for(int i=a.length()-1; i>=0; i--){ str+=a.charAt(a); } return str; }

2