Google Interview Question
Country: United States
private static String reformat(String s, int k) {
int len = s.length();
StringBuilder res = new StringBuilder();
int count = 0;
for (int i = len - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c != '-') {
if (count == k) {
res.append("-");
count = 0;
i++;
} else {
res.append(c);
count++;
}
}
}
return res.reverse().toString();
}
public String reformat(String str, int k){
if(str == null || str.length() == 0 || k <= 0 || k > str.length()){
return null;
}
if(k == str.length()){
return str;
}
int len = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) != '-'){
len++;
}
}
int rem = len % k;//0
StringBuilder bldr = new StringBuilder(str.length());
int i = 0;
while(i < rem){
if(str.charAt(i) != '-'){
bldr.append(str.charAt(i))
}
i++;
}
if(i != 0){
bldr.append('-');
}
while(i < str.length()){
int count = 0;
while(count < k){
if(str.charAt(i) != '-'){
bldr.append(str.charAt(i))
count++;
}
i++;
}
if(i < str.length()){
bldr.append('-');
}
}
return bldr.toString();
}
//O(N) time where N is the length of the input string. O(N) Space.
#include<stdio.h>
#include<stdlib.h>
void str_concat(char*s1,char*s2){
int p=0;
while(s1[p]!='\0'){
p++;
}
int q=0;
while(s2[q]!='\0'){
s1[p] = s2[q];
p++;
q++;
}
s1[p]='\0';
}
int main(){
char *A;
int k=0;
A = malloc(sizeof(char)*1000);
scanf("%s",A);
scanf("%d",&k);
char *result,*temp;
result = malloc(sizeof(char)*1000);
temp = malloc(sizeof(char)*1000);
int i=0,j=0,len=0;
while(A[i]!='\0'){
if(A[i]!='-'){
len++;
}
i++;
}
i=0;
while(i<(len%k)){
if(A[i]=='-'){
i++;
continue;
}
result[j]=A[i];
j++;
i++;
}
if(j>0){
result[j]='-';
j++;
}
result[j]='\0';
int l=0;
while(A[i]!='\0'){
if(A[i]=='-'){
i++;
continue;
}else{
if((l+1)%(k+1)==0){
temp[l]='-';
l++;
}
temp[l]=A[i];
l++;
}
i++;
}
temp[l]='\0';
str_concat(result,temp);
printf("\n%s",result);
printf("\n");
return 0;
}
Slight modification to libertythecoder's code. Please correct me if I'm wrong
public String formatString(String s , int k){
StringBuilder sb = new StringBuilder();
int counter = 0;
for(int i = 0; i < s.length() ; i++){
if(Character.isLetterOrDigit(s.charAt(i))){
sb.append(s.charAt(i));
counter++;
}
if(counter == 3){
counter = 0;
sb.append("-");
}
}
return sb.toString();
}
Passed tests
public String format(String S, int K) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < S.length(); i ++) {
if (S.charAt(i) != '-') {
builder.append(S.charAt(i));
}
}
StringBuilder result = new StringBuilder();
String ori = builder.toString();
int i = ori.length() - 1;
int stop = (ori.length() - 1) % K;
while (i >= 0) {
if (i % K == stop && i != ori.length() - 1)
result.append('-');
result.append(Character.toUpperCase(ori.charAt(i)));
i -= 1;
}
return result.reverse().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int num = sc.nextInt();
str = str.replaceAll("-", "");
if (str.length() > num) {
str = reFormatString(str, num);
}
System.out.println(str);
sc.close();
}
public static String reFormatString(String str, int num) {
str = str.replaceAll("-", "");
StringBuffer sb = new StringBuffer(str);
sb.reverse();
for (int i = num; i < sb.length(); i = i + num) {
sb.insert(i, "-");
i++;
}
sb.reverse();
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int num = sc.nextInt();
str = str.replaceAll("-", "");
if (str.length() > num) {
str = reFormatString(str, num);
}
System.out.println(str);
sc.close();
}
public static String reFormatString(String str, int num) {
str = str.replaceAll("-", "");
StringBuffer sb = new StringBuffer(str);
sb.reverse();
for (int i = num; i < sb.length(); i = i + num) {
sb.insert(i, "-");
i++;
}
sb.reverse();
return sb.toString();
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String input = sc.next();
int k = sc.nextInt();
System.out.println(Format(input, k) );
}
public static String Format(String args,int k)
{
StringBuilder s = new StringBuilder();
int count=0;
int len =0;
for(String str : args.split("-"))
{
len = len +str.length();
}
char [] chararr =args.toCharArray();
for(int i=chararr.length-1;i>=0;i--)
{
char c = chararr[i];
if(c!='-')
{
s.append(Character.toString(c));
count++;
if(count%k==0&& count!=len)
{
s.append("-");
}
}
}
return s.reverse().toString();
}
private static String formattedString(String original, int size){
if(original == null || size < 1 || original.length() < 1)
return "";
int length = original.length();
int currIndex = length - 1;
StringBuilder result = new StringBuilder(length + (length / size) + 1);
while(true){
int finalIndex = currIndex - size;
while(currIndex >= 0 && currIndex > finalIndex){
if(original.charAt(currIndex) == '-'){
finalIndex--;
}else{
result.insert(0, original.charAt(currIndex));
}
currIndex--;
}
if(currIndex > 0){
result.insert(0,'-');
}else{
break;
}
}
return result.toString();
}
From my point of view they want to "split" a string into groups separated by dash and tehy provide the number of elements in the group so assuming that please find below my solution:
//FUNCTION TO SPLIT A STRING WITH A DASH GIVEN THE NUMBER OF ELEMENTS PER GROUP
-(NSString *)getFormatString:(NSString *)string withSplitItems:(int)split{
NSMutableString *result = [NSMutableString new];
//REPLACE ALL DASHES SINCE THEY DO NOT MENTION TO KEEP IT
string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
int length = (int)[string length];
int j = -1;
//ITERATE BETWEEN ALL CHARACTERS IN THE STRING FROM THE END TO THE START
for(int i = length - 1; i >= 0; i--){
//IF OUR SECONDARY COUNTER IS EQUAL TO THE GIVEN INDEX SET A DASH
j++;
if(j == split){
result = [result stringByAppendingString:@"-"];
j = 0;
}
//ADD EACH CHARACTER
[result insertString:[string substringWithRange:NSMakeRange(i, 1)] atIndex:0];
}
return result;
}
public class StringGroup {
// ----------------------------------------------------------------
public static String groupString(String inp, int grpLen) {
String grp = "";
int stringLen = inp.length();
StringBuffer inpString = new StringBuffer();
for (int i = 0; i < inp.length(); i = i + grpLen) {
if (stringLen >= grpLen) {
stringLen = stringLen - grpLen;
grp = inp.substring(i, i + grpLen);
inpString.append(grp + "-");
} else {
grp = inp.substring(i, inp.length());
inpString.append(grp);
}
}
return inpString.toString();
}
public static void main(String[] args) {
String inp = "California";
groupString(inp, 3);
}
}
Relatively simple problem. Using StringBuilder (or StringBuffer) is the key here.
public class StringFormatLengthK {
public String reformatString(String input, int k){
if(input == null || input.length() == 0){
return null;
}
String[] arr = input.split("-");
StringBuilder sbTemp = new StringBuilder();
for(String str : arr){
sbTemp.append(str);
}
String plainString = sbTemp.toString();
System.out.println("plainString: "+plainString);
int counter = 1;
StringBuilder sb = new StringBuilder();
for(int i = plainString.length()-1; i >= 0; i--){
String str = plainString.substring(i, i+1);
sb.append(str);
if(counter == k) {
sb.append("-");
counter = 0;
}
counter++;
}
String lastChar = sb.substring(sb.length()-1);
if("-".equals(lastChar)){
sb.deleteCharAt(sb.length()-1);
}
sb.reverse();
return sb.toString();
}
public static void main(String[] args) {
StringFormatLengthK stringFormatLengthK = new StringFormatLengthK();
String input = "2-4a0r7-4k";
String reformattedString = stringFormatLengthK.reformatString(input, 5);
System.out.println("reformatted: "+ reformattedString);
}
}
public static String split(String input, int k){
if(input==null){
return null;
}
int strLength = input.length();
if(strLength<=k){
return input;
}
StringBuilder stringBuilder = new StringBuilder();
int count= 0;
for(int i=0;i<strLength;i++){
char current = input.charAt(i);
if(count<k && current!='-'){
stringBuilder.append(current);
count++;
}else if (count==k && current != '-'){
stringBuilder.append('-').append(current);
count=0;
}
}
return stringBuilder.toString();
}
public class Main {
public static void main(String[] args) {
// write your code here
String unformatted ="2k-432iz-kdf";
Main main = new Main();
System.out.println(main.formatInSectionsOfSize(unformatted, 3));
}
public String formatInSectionsOfSize(String incoming, int sectionSize) {
LinkedList<Character> chars = new LinkedList<Character>();
for(int i = 0; i < incoming.length(); i++) {
char current = incoming.charAt(i);
if(current != '-') {
chars.addLast(current);
}
}
StringBuilder stringBuilder = new StringBuilder();
int firstSection = chars.size() % sectionSize;
if(firstSection > 0) {
for(int i = 0; i < firstSection; i++) {
stringBuilder.append(chars.removeFirst());
}
stringBuilder.append("-");
}
int remainingSize = chars.size();
for(int i = 0; i < remainingSize; i++ ) {
stringBuilder.append(chars.removeFirst());
if( (i % sectionSize) == (sectionSize - 1) && i != (remainingSize - 1)) {
stringBuilder.append("-");
}
}
return stringBuilder.toString();
}
}
String A = "2-4a0r7-4k-asfasf-112";
int K = 3;
String _without_hypens = "";
StringBuilder sb = new StringBuilder();
StringBuilder _hyphen_appended = new StringBuilder();
int count = 0;
String _with_hyphens_rev = "";
String _with_hyphens = "";
//loop to get all the characters without hyphens
for(int i=0; i<A.length();i++){
if(!(A.substring(i, i+1).equals("-"))){
sb.append(A.substring(i,i+1));
}
}
_without_hypens = sb.toString();
//loop from the last character to get assign hyphens after crossing K characters
for(int j=_without_hypens.length() -1; j>=0; j--){
_hyphen_appended.append(_without_hypens.substring(j, j+1));
count+=1;
if(count == K && j != 0){
_hyphen_appended.append("-");
count = 0;
}
}
_with_hyphens_rev = _hyphen_appended.toString();
//loop to reverse the string
for(int k = _with_hyphens_rev.length() -1; k>=0; k--){
_with_hyphens+=_with_hyphens_rev.substring(k, k+1);
}
public String Stringformatter(String A, int K){
String _without_hypens = "";
StringBuilder sb = new StringBuilder();
StringBuilder _hyphen_appended = new StringBuilder();
int count = 0;
String _with_hyphens_rev = "";
String _with_hyphens = "";
//loop to get all the characters without hyphens
for(int i=0; i<A.length();i++){
if(!(A.substring(i, i+1).equals("-"))){
sb.append(A.substring(i,i+1));
}
}
_without_hypens = sb.toString();
//loop from the last character to get assign hyphens after crossing K characters
for(int j=_without_hypens.length() -1; j>=0; j--){
_hyphen_appended.append(_without_hypens.substring(j, j+1));
count+=1;
if(count == K && j != 0){
_hyphen_appended.append("-");
count = 0;
}
}
_with_hyphens_rev = _hyphen_appended.toString();
//loop to reverse the string
for(int k = _with_hyphens_rev.length() -1; k>=0; k--){
_with_hyphens+=_with_hyphens_rev.substring(k, k+1);
}
return _with_hyphens;
}
public String reformat(String s, int k) {
if (s.length() == 0 || k <= 0 || k > s.length() || s == null) {
return null;
}
if (k == s.length()) {
return s;
}
return new StringBuilder(new StringBuilder(s).reverse().toString().replaceAll("-", "").replaceAll("(.{" + k + "})", "$1-").replaceAll("-$", "")).reverse().toString();
}
- Upen October 25, 2016