howardkhl
BAN USERpublic class EqualSpacesInWords {
public static void main(String[] args) {
String s1 = "This is an example";
String s2 = equalSpacesInWords( s1 );
System.out.println( s2 );
}
private static String equalSpacesInWords( String s ) {
String formatted = "";
List<String> listStr = new ArrayList<String>();
String word = "";
char[] a = s.trim().toCharArray();
int countSpaces = 0;
boolean processWord = true;
for( int i = 0; i < a.length; i++ ) {
if( processWord ) {
if( a[i] != ' ' ) {
word += a[i];
if( i == a.length - 1 ) {
listStr.add( word );
}
}
else {
countSpaces += 1;
processWord = false;
}
}
else {
if( a[i] == ' ' ) {
countSpaces += 1;
}
else {
listStr.add( word );
word = "";
word += a[i];
processWord = true;
}
}
}
int formattedSpaces = countSpaces / listStr.size();
while( !listStr.isEmpty() ) {
formatted += listStr.remove(0);
if( !listStr.isEmpty() ) {
for( int i = 0; i < formattedSpaces; i++ ) {
formatted += " ";
}
}
}
return formatted;
}
}
Assume ints are sorted.
int findNonRepeatedInt(int[] intArray) {
if( intArray == null )
throw new NullPointerException();
if( intArray.length == 1 )
return intArray[0];
int nonRepeatedInt = -1;
try {
for( int i = 0; i < intArray.length; i += 2 ) {
if( intArray.length - i == 1 ) {
return intArray[i];
}
if( intArray[i] != intArray[i + 1] ) {
nonRepeatedInt = intArray[i];
break;
}
}
} catch( ArrayIndexOutOfBoundsException e ) {
System.out.println( "out of bound" );
}
return nonRepeatedInt;
}
private static int sumCharArray(char[] charArray) {
int sum = 0, num = 0;
for( int i = 0; i < charArray.length; i++ ) {
if( Character.isDigit( charArray[i] ) ) {
num = num * 10 + ( charArray[i] - '0' );
if( charArray.length - i == 1 ) {
sum += num;
}
}
else {
if( num > 0 ) {
sum += num;
num = 0;
}
}
}
return sum;
}
import java.util.Arrays;
public class SortCharArray {
public static void main( String args[] ) {
char[] a = { 'b', 'f', 'c', 'z', 'a', 'd', 'x', 'h' };
char[] b = charCountingSort( a );
for( int i = 0; i < b.length; i++ ) {
System.out.print( b[i] + " " );
}
}
private static char[] charCountingSort(char[] a) {
int[] count = new int[26];
char[] b = new char[a.length];
for( int i = 0; i < count.length; i++ ) {
count[i] = 0;
}
for( char c : a ) {
count[c - 'a']++;
}
int current = 0;
for( int i = 0; i < count.length; i++ ) {
if( count[i] != 0 ) {
Arrays.fill( b, current, current + count[i], (char)(i + 'a') );
current++;
}
}
return b;
}
}
Does it work for: [2,2,3,3,3,4,4,4,5,5,5]
- howardkhl January 16, 2013